|
| 1 | +//Runtime: 12 ms, faster than 71.71% of C++ online submissions for Regions Cut By Slashes. |
| 2 | +//Memory Usage: 9.9 MB, less than 50.00% of C++ online submissions for Regions Cut By Slashes. |
| 3 | +/Approach 1: Union-Find |
| 4 | +class DSU{ |
| 5 | +public: |
| 6 | + vector<int> parent; |
| 7 | + |
| 8 | + DSU(int N){ |
| 9 | + parent = vector<int>(N); |
| 10 | + iota(parent.begin(), parent.end(), 0); |
| 11 | + } |
| 12 | + |
| 13 | + int find(int x){ |
| 14 | + if(parent[x] != x){ |
| 15 | + parent[x] = find(parent[x]); |
| 16 | + } |
| 17 | + return parent[x]; |
| 18 | + } |
| 19 | + |
| 20 | + void unite(int x, int y){ |
| 21 | + parent[find(x)] = find(y); |
| 22 | + } |
| 23 | +}; |
| 24 | + |
| 25 | +class Solution { |
| 26 | +public: |
| 27 | + int regionsBySlashes(vector<string>& grid) { |
| 28 | + int N = grid.size(); |
| 29 | + //0,1,2,3 for north, west, east, south |
| 30 | + DSU dsu = DSU(4*N*N); |
| 31 | + for(int r = 0; r < N; r++){ |
| 32 | + for(int c = 0; c < N; c++){ |
| 33 | + //one grid has max of 4 regions |
| 34 | + int root = 4 * (r*N+c); |
| 35 | + char val = grid[r][c]; |
| 36 | + //Note here it is "!=" |
| 37 | + if(val != '\\'){ |
| 38 | + //north and west are connected |
| 39 | + dsu.unite(root + 0, root + 1); |
| 40 | + //east and south are connected |
| 41 | + dsu.unite(root + 2, root + 3); |
| 42 | + } |
| 43 | + if(val != '/'){ |
| 44 | + //north and east are connected |
| 45 | + dsu.unite(root + 0, root + 2); |
| 46 | + //west and south are connected |
| 47 | + dsu.unite(root + 1, root + 3); |
| 48 | + } |
| 49 | + |
| 50 | + //connecting with other grids |
| 51 | + //connect south of current grid and north of the grid below |
| 52 | + if(r + 1 < N) |
| 53 | + dsu.unite(root + 3, (root + 4*N) + 0); |
| 54 | + //north and upper's south |
| 55 | + if(r - 1 >= 0) |
| 56 | + dsu.unite(root + 0, (root - 4*N) + 3); |
| 57 | + //east and rhs's west |
| 58 | + if(c + 1 < N) |
| 59 | + dsu.unite(root + 2, (root + 4) + 1); |
| 60 | + //west and lhs's east |
| 61 | + if(c - 1 >= 0) |
| 62 | + dsu.unite(root + 1, (root - 4) + 2); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + int ans = 0; |
| 67 | + for(int x = 0; x < 4*N*N; x++){ |
| 68 | + if(dsu.find(x) == x) |
| 69 | + ans++; |
| 70 | + } |
| 71 | + |
| 72 | + return ans; |
| 73 | + } |
| 74 | +}; |
0 commit comments