959. The area is divided by slashes
In a 1 x 1
grid consisting of N x N
grid grid
, each 1 x 1
block made /
, \
consisting of or spaces. These characters divide the square into co-sided areas.
(Note that the backslash character is the escape, so \
by "\\"
express.).
Returns the number of regions.
Example 1:
输入:
[
" /",
"/ "
]
输出:2
解释:2x2 网格如下:
Example 2:
输入:
[
" /",
" "
]
输出:1
解释:2x2 网格如下:
Example 3:
输入:
[
"\\/",
"/\\"
]
输出:4
解释:(回想一下,因为 \ 字符是转义的,所以 "\\/" 表示 \/,而 "/\\" 表示 /\。)
2x2 网格如下:
Example 4:
输入:
[
"/\\",
"\\/"
]
输出:5
解释:(回想一下,因为 \ 字符是转义的,所以 "/\\" 表示 /\,而 "\\/" 表示 \/。)
2x2 网格如下:
Example 5:
输入:
[
"//",
"/ "
]
输出:3
解释:2x2 网格如下:
prompt:
1 <= grid.length == grid[0].length <= 30
grid[i][j]
Shi'/'
,'\'
, or' '
.
Method 1: Collect and check
Problem-solving ideas
The picture below is from the "Official Answer", I am too lazy to draw it.
- This question is ultimately a question of "connectivity". As shown, the each cell is divided into
4
regions. - A total of
n = len * len * 4
areas, whereinlen
asgrid
the length. - An initial state,
n
a cell are not connected, i.e. dividedn
areas. - Traversal
grid
(Note:grid[i]
strings, we need to traversegrid[i]
every character)- Encountered
'/'
when: connectivity[0]
and[3]
connectivity[1]
and[2]
- Encountered
'\'
when: connectivity[0]
and[1]
connectivity[2]
and[3]
- Encountered
' '
when: communication[0]
,[1]
,[2]
,[3]
- Encountered
- In addition,
[1]
the cells on the right are connected,[2]
and the cells below are connected, and they need to be connected separately. (From left to right because, from there down, so just processed右
and the下
two directions) - After each connection, the number of regions will be
n = n - 1
returned after the traversal is completedn
Reference Code
public int regionsBySlashes(String[] grid) {
int len = grid.length;
int n = len * len * 4;
UnionFind unionFind = new UnionFind(n);
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
int num = (i * len + j) * 4;
char ch = grid[i].charAt(j);
if (ch == '/') {
unionFind.union(num, num + 3);
unionFind.union(num + 1, num + 2);
} else if (ch == '\\') {
unionFind.union(num, num + 1);
unionFind.union(num + 2, num + 3);
} else {
unionFind.union(num, num + 1);
unionFind.union(num, num + 2);
unionFind.union(num, num + 3);
}
if (i < len - 1) {
unionFind.union(num + 2, num + len * 4);
}
if (j < len - 1) {
unionFind.union(num + 1, num + 7);
}
}
}
return unionFind.getCount();
}
class UnionFind {
private int[] parent;
private int count;
public UnionFind(int n) {
parent = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public void union(int x, int y) {
int rootX = find(x), rootY = find(y);
if (rootX == rootY) {
return;
}
parent[rootX] = rootY;
count--;
}
public int find(int x) {
return parent[x] == x ? parent[x] : (parent[x] = find(parent[x]));
}
public int getCount() {
return count;
}
}
Results of the