959. 由斜杠划分区域(并查集)
959. 由斜杠划分区域
在由 1 x 1 方格组成的 n x n 网格 grid 中,每个 1 x 1 方块由 '/'、'\' 或空格构成。这些字符会将方块划分为一些共边的区域。
给定网格 grid 表示为一个字符串数组,返回 区域的数量 。
请注意,反斜杠字符是转义的,因此 '\' 用 '\\' 表示。
示例 1:

输入:grid = [" /","/ "] 输出:2
示例 2:

输入:grid = [" /"," "] 输出:1
示例 3:

输入:grid = ["/\\","\\/"] 输出:5 解释:回想一下,因为 \ 字符是转义的,所以 "/\\" 表示 /\,而 "\\/" 表示 \/。
提示:
n == grid.length == grid[i].length1 <= n <= 30grid[i][j]是'/'、'\'、或' '
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <string> 5 6 using namespace std; 7 8 class UionFind { 9 public: 10 void initUionFind(int n) { 11 parent.resize(n); 12 count = n; 13 for (int i = 0; i < n; i++) { 14 parent[i] = i; 15 } 16 } 17 int findRoot(int x) { 18 while (x != parent[x]) { 19 parent[x] = parent[parent[x]]; 20 x = parent[x]; 21 } 22 return x; 23 } 24 void unify(int x, int y) { 25 int xRoot = findRoot(x); 26 int yRoot = findRoot(y); 27 if (xRoot == yRoot) { 28 return; 29 } 30 parent[xRoot] = yRoot; 31 count--; 32 return; 33 } 34 int getCount() { 35 return count; 36 } 37 private: 38 vector<int> parent; 39 int count; 40 }; 41 42 class Solution : public UionFind { 43 public: 44 int regionsBySlashes(vector<string>& grid) { 45 int N = grid.size(); 46 int n = 4 * N * N; // 将一个小方格划分成4个网格 47 initUionFind(n); 48 for (int i = 0; i < N; i++) { 49 for (int j = 0; j < N; j++) { 50 int index = 4 * (i * N + j); // 二维网格转换为一维 51 char ch = grid[i][j]; 52 // 1、方格内合并 53 if (ch == '/') { // 合并0、3,合并1、2 54 unify(index, index + 3); 55 unify(index + 1, index + 2); 56 } else if (ch == '\\') { // 合并0、1,合并2、3 57 unify(index, index + 1); 58 unify(index + 2, index + 3); 59 } else { // 合并0、1、2、3 60 unify(index, index + 1); 61 unify(index + 1, index + 2); 62 unify(index + 2, index + 3); 63 } 64 // 2、方格间合并 65 if (j + 1 < N) { // 向右合并, 1(当前)、3(右下一列) 66 unify(index + 1, 4 * (i * N + j + 1) + 3); 67 } 68 if (i + 1 < N) { // 向下合并, 2(当前)、0(下一行) 69 unify(index + 2, 4 * ((i + 1) * N + j)); 70 } 71 } 72 } 73 return getCount(); 74 } 75 }; 76 77 int main() 78 { 79 /* 80 * 测试用例1:grid = [" /","/ "],期望输出:2 81 * 测试用例2:grid = [" /"," "],期望输出:1 82 * 测试用例3:grid = ["/\\","\\/"],期望输出:5 83 */ 84 Solution *test = new Solution(); 85 vector<string> grid = {" /", "/ "}; 86 int expect = 2; 87 int ans = test->regionsBySlashes(grid); 88 cout << "expect ans:" << expect << ", actual ans:"<< ans << endl; 89 return 0; 90 }
浙公网安备 33010602011771号