给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
思路:并查集
class Solution {
// 并查集
class UnionFind{
int[] parent;
int[] rank;
int count;
public UnionFind(char[][] grid) {
this.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++;
}
rank[i * n + j] = 0;
}
}
}
public int find(int p) {
//路劲压缩算法,不处理rank
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p,int q) {
int proot = find(p);
int qroot = find(q);
if (proot == qroot)
return;
if (rank[proot] < rank[qroot]) {
parent[proot] = qroot;
} else if (rank[proot] > rank[qroot]) {
parent[qroot] = proot;
} else {
parent[qroot] = proot;
rank[proot] += 1;
}
--count;
}
public int getCount() {
return this.count;
}
}
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 ) {
return 0;
}
int nr = grid.length;
int nc = grid[0].length;
int numIs = 0;
UnionFind uf = new UnionFind(grid);
for (int i = 0; i < nr;i++) {
for (int j = 0;j < nc;j++) {
if (grid[i][j] == '1') {
grid[i][j] = '0';
// 处理当前元素的下方元素
if (i + 1 < nr && grid[i+1][j] == '1')
uf.union(i*nc + j,(i+1)*nc + j);
// 处理右边
if (j + 1 < nc && grid[i][j+1] == '1')
uf.union(i*nc + j,i*nc + (j+1));
}
}
}
return uf.getCount();
}
}