-
Notifications
You must be signed in to change notification settings - Fork 2
/
200.number-of-islands.java
93 lines (80 loc) · 2.42 KB
/
200.number-of-islands.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* @lc app=leetcode id=200 lang=java
*
* [200] Number of Islands
*/
// @lc code=start
class Solution {
class UnionFind {
private int count = 0;
private int[] parent;
private int[] rank;
public UnionFind(char[][] grid) {
count = 0;
int m = grid.length;
int n = grid[0].length;
parent = new int[m * n];
rank = new int[m * n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
parent[i * n + j] = i * n + j;
count++;
}
}
}
}
public int find(int p) {
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) {
return;
}
if (rank[rootQ] > rank[rootP]) {
parent[rootP] = rootQ;
} else {
parent[rootQ] = rootP;
}
count--;
}
public int getCount() {
return count;
}
}
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
UnionFind uf = new UnionFind(grid);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
grid[i][j] = '0';
if (i - 1 >= 0 && grid[i - 1][j] == '1') {
uf.union(i * n + j, (i - 1) * n + j);
}
if (j - 1 >= 0 && grid[i][j - 1] == '1') {
uf.union(i * n + j, i * n + (j - 1));
}
if (i + 1 < m && grid[i + 1][j] == '1') {
uf.union(i * n + j, (i + 1) * n + j);
}
if (j + 1 < n && grid[i][j + 1] == '1') {
uf.union(i * n + j, i * n + (j + 1));
}
}
}
}
return uf.getCount();
}
}
// @lc code=end