按照如图所示分割一个正方形,问可以分成多少块
sol:
1、并查集
最上方编号为0,右边为1,下面为2,左边为3,根据是否是左斜线和右斜线来合并。然后左右合并,上下合并
public class Leetcode0959 {
int n;
int[] parent;
int find(int x) {
if (x == parent[x]) return x;
return parent[x] = find(parent[x]);
}
void union(int x, int y) {
int fx = find(x);
int fy = find(y);
if (fx != fy) parent[fx] = fy;
}
int getPos(int x, int y, int num) {
return 4 * (x * n + y) + num;
}
public int regionsBySlashes(String[] grid) {
n = grid.length;
parent = new int[n * 4 * n];
for (int i = 0; i < parent.length; i++) parent[i] = i;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length(); j++) {
char ch = grid[i].charAt(j);
int pos0 = getPos(i, j, 0);
int pos1 = getPos(i, j, 1);
int pos2 = getPos(i, j, 2);
int pos3 = getPos(i, j, 3);
if (ch == ' ') {
union(pos0, pos1);
union(pos1, pos2);
union(pos2, pos3);
} else if (ch == '/') {
union(pos0, pos3);
union(pos1, pos2);
} else if (ch == '\\') {
union(pos0, pos1);
union(pos2, pos3);
} else {
//cannot reach here
}
if (i > 0) {
int upPos = getPos(i - 1, j, 2);
union(pos0, upPos);
}
if (j > 0) {
int leftPos = getPos(i, j - 1, 1);
union(pos3, leftPos);
}
}
}
int res = 0;
for (int i = 0; i < parent.length; i++) if (parent[i] == i) res++;
return res;
}
}
2、还有一种是使用dfs,这种我没有去写,有时间再试试吧