-
Notifications
You must be signed in to change notification settings - Fork 0
/
Regions Cut By Slashes.java
66 lines (61 loc) · 1.78 KB
/
Regions Cut By Slashes.java
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
class Solution {
int[] parent;
int[] rank;
int count;
public int regionsBySlashes(String[] grid) {
int rows = grid.length;
int dots = rows+1;
parent = new int[dots*dots];
rank = new int[dots*dots];
for (int i=0; i<parent.length; i++){
parent[i] = i;
rank[i] = 1;
}
for (int i=0; i<dots; i++){
for (int j=0; j<dots; j++){
if (i==0 || j==0 || i==rows || j==rows){
int cells = i * dots + j;
union(0, cells);
}
}
}
for (int i=0; i<rows; i++){
char[] ch = grid[i].toCharArray();
for (int j=0; j<ch.length; j++){
if (ch[j] == '\\'){
int cell1 = i* dots+ j;
int cell2 = (i+1)*dots + (j+1);
union(cell1, cell2);
} else if (ch[j] == '/'){
int cell1 = (i+1)*dots + j;
int cell2 = i*dots + (j+1);
union(cell1, cell2);
}
}
}
return count;
}
public void union(int a, int b){
int parentA = find(a);
int parentB = find(b);
if (parentA == parentB){
count++;
} else {
if (rank[parentA] > rank[parentB]){
parent[parentB] = parentA;
} else if (rank[parentA] < rank[parentB]){
parent[parentA] = parentB;
} else {
parent[parentB] = parentA;
rank[parentA]++;
}
}
}
public int find(int a){
if(parent[a]==a)
return a;
int temp = find(parent[a]);
parent[a] = temp;
return temp;
}
}