Skip to content

Commit b565d59

Browse files
committed
Keeping track of parents and unioning only when 1 is present
1 parent 286843d commit b565d59

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

UnionFind/numIslands.java

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
class Solution {
2+
/*
3+
This problem reduces to number of connected componenets with 1's as the components.
4+
*/
5+
int[][] distance = {{1,0}, {-1,0}, {0,1}, {0,-1}};
6+
public int numIslands(char[][] grid) {
7+
8+
if (grid == null || grid.length == 0 || grid[0].length == 0) {
9+
return 0;
10+
}
11+
12+
UnionFind uf = new UnionFind(grid);
13+
int row = grid.length;
14+
int col = grid[0].length;
15+
16+
for (int i=0; i<row; i++) {
17+
for (int j=0; j< col; j++) {
18+
if (grid[i][j] == '1') {
19+
for (int[] d: distance) {
20+
int x = i + d[0];
21+
int y = j + d[1];
22+
if (x >= 0 && x < row && y >= 0 && y < col && grid[x][y] == '1') {
23+
int id1 = i*col + j;
24+
int id2 = x*col + y;
25+
uf.union(id1, id2);
26+
}
27+
}
28+
}
29+
}
30+
}
31+
32+
33+
return uf.count;
34+
}
35+
}
36+
37+
class UnionFind{
38+
int parent[];
39+
int m, n;
40+
int count;
41+
public UnionFind(char[][] grid) {
42+
m = grid.length;
43+
n = grid[0].length;
44+
parent = new int[m*n];
45+
46+
for (int i=0; i<m; i++) {
47+
for (int j=0; j <n; j++) {
48+
if (grid[i][j] == '1') {
49+
int id = i*n + j; //this forms the 'id' in sequential format only for cells that are 1
50+
parent[id] = id;
51+
count++;
52+
53+
}
54+
}
55+
}
56+
}
57+
58+
public int find(int p) {
59+
while(parent[p] != p) {
60+
p = parent[p];
61+
}
62+
return p;
63+
}
64+
65+
public void union(int p, int q) {
66+
int pParent = find(p);
67+
int qParent = find(q);
68+
if (pParent != qParent) {
69+
parent[qParent] = pParent;
70+
count--;
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)