Skip to content

Commit 24221e6

Browse files
number of islands using union find
1 parent 120d72e commit 24221e6

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package medium;
2+
3+
/**
4+
* Created by fishercoder1534 on 9/30/16.
5+
*/
6+
7+
//Inspired by this post: https://discuss.leetcode.com/topic/39980/1d-union-find-java-solution-easily-generalized-to-other-problems
8+
public class NumberOfIslandsUnionFind {
9+
10+
class UnionFind{
11+
int count;
12+
int m, n;
13+
int[] ids;
14+
15+
public UnionFind(char[][] grid){
16+
m = grid.length;
17+
n = grid[0].length;
18+
ids = new int[m*n];
19+
for(int i = 0; i < m; i++){
20+
for(int j = 0; j < n; j++){
21+
if(grid[i][j] == '1') {
22+
count++;
23+
ids[i*n+j] = i*n+j;
24+
}
25+
}
26+
}
27+
}
28+
29+
public void union(int i, int j){
30+
int x = find(ids, i);
31+
int y = find(ids, j);
32+
if(x != y) {//note: this is when x != y, only in this case, we should union these two nodes, which makes sense naturally.
33+
count--;
34+
ids[x] = y;
35+
}
36+
}
37+
38+
public int find(int[] ids, int i){
39+
if(ids[i] == i) return i;
40+
return find(ids, ids[i]);
41+
}
42+
}
43+
44+
public int numIslands(char[][] grid) {
45+
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
46+
int[] dirs = new int[]{0,1,0,-1,0};
47+
UnionFind uf = new UnionFind(grid);
48+
int m = grid.length, n = grid[0].length;
49+
for(int i = 0; i < m; i++){
50+
for(int j = 0; j < n; j++){
51+
if(grid[i][j] == '1'){
52+
for(int k = 0; k < 4; k++){
53+
int x = i+dirs[k];
54+
int y = j+dirs[k+1];
55+
if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1'){
56+
int id1 = i*n+j;
57+
int id2 = x*n+y;
58+
uf.union(id1, id2);
59+
}
60+
}
61+
}
62+
}
63+
}
64+
return uf.count;
65+
}
66+
}

0 commit comments

Comments
 (0)