959 Regions Cut By Slashes
1. Question
[
" /",
"/ "
]
Output: 2Input:
[
" /",
" "
]
Output: 12. Implementation
3. Time & Space Complexity
Last updated
[
" /",
"/ "
]
Output: 2Input:
[
" /",
" "
]
Output: 1Last updated
class Solution {
public int regionsBySlashes(String[] grid) {
int n = grid.length;
int size = n * n * 4;
UnionFind uf = new UnionFind(size);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > 0) uf.union(id(i - 1, j, 2, n), id(i, j, 0, n));
if (j > 0) uf.union(id(i, j - 1, 1, n),id(i, j, 3, n));
if (grid[i].charAt(j) == '/') {
uf.union(id(i, j, 0, n), id(i, j, 3, n));
uf.union(id(i, j, 1, n), id(i, j, 2, n));
}
else if (grid[i].charAt(j) == '\\') {
uf.union(id(i, j, 0, n), id(i, j, 1, n));
uf.union(id(i, j, 2, n), id(i, j, 3, n));
}
else {
uf.union(id(i, j, 0, n), id(i, j, 1, n));
uf.union(id(i, j, 2, n), id(i, j, 3, n));
uf.union(id(i, j, 0, n), id(i, j, 3, n));
}
}
}
return uf.count;
}
public int id(int row, int col, int offset, int n) {
return (row * n + col) * 4 + offset;
}
class UnionFind {
int[] root;
int[] size;
int count;
public UnionFind(int n) {
root = new int[n];
size = new int[n];
count = n;
for (int i = 0; i < n; i++) {
root[i] = i;
size[i] = 1;
}
}
public int find(int node) {
while (node != root[node]) {
node = root[node];
}
return node;
}
public void union(int i , int j) {
int p = find(i);
int q = find(j);
if (p == q) return;
if (size[p] < size[q]) {
root[p] = q;
size[q] += size[p];
}
else {
root[q] = p;
size[p] += size[q];
}
--count;
}
}
}