[Leetcode] Problem 959 - Regions Cut By Slashes

In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space. These characters divide the square into contiguous regions.

(Note that backslash characters are escaped, so a \ is represented as “\\“.)

Return the number of regions.

Example

No.1

Input:

1
2
3
4
[
" /",
"/ "
]

Output: 2

Explanation: The 2x2 grid is as follows:

0tEV1A.png

No.2

Input:

1
2
3
4
[
" /",
" "
]

Output: 1

Explanation: The 2x2 grid is as follows:

0tE8pj.png

No.3

Input:

1
2
3
4
[
"\\/",
"/\\"
]

Output: 4

Explanation: (Recall that because \ characters are escaped, “\\/“ refers to \/, and “/\\“ refers to /\.)
The 2x2 grid is as follows:

0tEycR.png

No.4

Input:

1
2
3
4
[
"/\\",
"\\/"
]

Output: 5

Explanation: (Recall that because \ characters are escaped, “/\\“ refers to /\, and “\\/“ refers to \/.)
The 2x2 grid is as follows:

0tE7jI.png

No.5

Input:

1
2
3
4
[
"//",
"/ "
]

Output: 3

Explanation: The 2x2 grid is as follows:

0tVpgs.png

Note

  1. 1 <= grid.length == grid[0].length <= 30
  2. grid[i][j] is either ‘/‘, ‘\‘, or ‘ ‘.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class UnionFind {
private int[] id;
private int[] size;
private int count;

public UnionFind(int n) {
this.id = new int[n];
this.size = new int[n];
count = n;

for (int i = 0; i < n; i++) {
id[i] = i;
size[i] = 1;
}
}

public int count() {
return count;
}

public boolean union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);

if (pRoot == qRoot)
return false;

if (size[pRoot] < size[qRoot]) {
id[pRoot] = qRoot;
size[qRoot] += size[pRoot];
} else {
id[qRoot] = pRoot;
size[pRoot] += size[qRoot];
}

count--;

return true;
}

public int find(int p) {
while (p != id[p])
p = id[p];

return p;
}
}

public int regionsBySlashes(String[] grid) {
int n = grid.length;
UnionFind uf = new UnionFind(4 * n * n);

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int idx = 4 * (i * n + j);

if (grid[i].charAt(j) == '/') {
uf.union(idx, idx + 3);
uf.union(idx + 1, idx + 2);
} else if (grid[i].charAt(j) == '\\') {
uf.union(idx, idx + 1);
uf.union(idx + 2, idx + 3);
} else {
uf.union(idx, idx + 1);
uf.union(idx + 1, idx + 2);
uf.union(idx + 2, idx + 3);
}

if (i < n - 1)
uf.union(idx + 2, idx + 4 * n);

if (j < n - 1)
uf.union(idx + 1, idx + 4 + 3);
}
}

return uf.count();
}