Skip to content

Commit 4c03cc1

Browse files
committed
union find and checking in 4 directions whenever new point is added
1 parent b565d59 commit 4c03cc1

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

UnionFind/numIslands2.java

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
class Solution {
2+
/*
3+
To represent a list of islands, we use trees. i.e., a list of parents. T
4+
This helps us find the identifier of an island faster. If parents[c] = p means the parent of node c is p,
5+
we can climb up the parent chain to find out the identifier of an island, i.e., which island this point belongs to:
6+
Do root[root[roots[c]]]... until root[c] == c
7+
Union is only changing the root parent, so it is O(1).
8+
FIND operation is proportional to the depth of the tree. If N is the number of points added, the average running time is O(logN),
9+
and a sequence of 4N operations i.e. 4 directions whenever a new point is added takes O(NlogN).
10+
If there is no balancing, the worse case could be O(N^2).
11+
12+
*/
13+
int[][] distance = {{1,0}, {-1,0}, {0,1}, {0,-1}};
14+
public List<Integer> numIslands2(int m, int n, int[][] positions) {
15+
List<Integer> res = new ArrayList<>();
16+
if (m <= 0 || n <= 0) {
17+
return res;
18+
}
19+
int count = 0;
20+
int[][] grid = new int[m][n];
21+
int[] parents = new int[m*n];
22+
23+
Arrays.fill(parents, -1);
24+
for (int[] p: positions) {
25+
int id = p[0]*n + p[1];
26+
27+
if (parents[id] != -1) { // duplicate position
28+
res.add(count);
29+
continue;
30+
}
31+
count++;
32+
parents[id] = id;
33+
34+
for (int[] dir: distance) {
35+
int x = p[0] + dir[0];
36+
int y = p[1] + dir[1];
37+
int id2 = x*n + y;
38+
if (x <0 || y <0 || x >= m || y>= n || parents[id2] == -1) {
39+
continue;
40+
}
41+
// unioning two islands
42+
int id2Parent = find(parents, id2);
43+
if (id != id2Parent) { // if neighbour is in another island
44+
parents[id] = id2Parent;
45+
id = id2Parent;
46+
count--;
47+
}
48+
49+
}
50+
res.add(count);
51+
}
52+
return res;
53+
}
54+
55+
public int find(int[] parent, int p) {
56+
while(p != parent[p]) {
57+
parent[p] = parent[parent[p]]; //adding one line for path compression
58+
p = parent[p];
59+
60+
}
61+
return p;
62+
}
63+
64+
65+
}
66+

0 commit comments

Comments
 (0)