|
| 1 | +// Time: O(n^2) |
| 2 | +// Space: O(n^2) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int regionsBySlashes(vector<string>& grid) { |
| 7 | + UnionFind union_find(grid.size() * grid.size() * 4); |
| 8 | + for (int i = 0; i < grid.size(); ++i) { |
| 9 | + for (int j = 0; j < grid[0].size(); ++j) { |
| 10 | + if (i) { |
| 11 | + union_find.union_set(index(grid.size(), i - 1, j, S), |
| 12 | + index(grid.size(),i, j, N)); |
| 13 | + } |
| 14 | + if (j) { |
| 15 | + union_find.union_set(index(grid.size(), i, j - 1, E), |
| 16 | + index(grid.size(), i, j, W)); |
| 17 | + } |
| 18 | + if (grid[i][j] != '/') { |
| 19 | + union_find.union_set(index(grid.size(), i, j, N), |
| 20 | + index(grid.size(), i, j, E)); |
| 21 | + union_find.union_set(index(grid.size(), i, j, S), |
| 22 | + index(grid.size(), i, j, W)); |
| 23 | + } |
| 24 | + if (grid[i][j] != '\\') { |
| 25 | + union_find.union_set(index(grid.size(), i, j, W), |
| 26 | + index(grid.size(), i, j, N)); |
| 27 | + union_find.union_set(index(grid.size(), i, j, E), |
| 28 | + index(grid.size(), i, j, S)); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + return union_find.size(); |
| 33 | + } |
| 34 | + |
| 35 | +private: |
| 36 | + enum NODES {N, E, S, W}; |
| 37 | + |
| 38 | + class UnionFind { |
| 39 | + public: |
| 40 | + UnionFind(const int n) : set_(n), count_(n) { |
| 41 | + iota(set_.begin(), set_.end(), 0); |
| 42 | + } |
| 43 | + |
| 44 | + int find_set(const int x) { |
| 45 | + if (set_[x] != x) { |
| 46 | + set_[x] = find_set(set_[x]); // Path compression. |
| 47 | + } |
| 48 | + return set_[x]; |
| 49 | + } |
| 50 | + |
| 51 | + void union_set(const int x, const int y) { |
| 52 | + int x_root = find_set(x), y_root = find_set(y); |
| 53 | + if (x_root != y_root) { |
| 54 | + set_[min(x_root, y_root)] = max(x_root, y_root); |
| 55 | + --count_; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + int size() const { |
| 60 | + return count_; |
| 61 | + } |
| 62 | + |
| 63 | + private: |
| 64 | + vector<int> set_; |
| 65 | + int count_; |
| 66 | + }; |
| 67 | + |
| 68 | + int index(int n, int i, int j, int k) { |
| 69 | + return (i * n + j) * 4 + k; |
| 70 | + } |
| 71 | +}; |
0 commit comments