package com.heu.wsq.leetcode.bingchaji;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 200. 岛屿数量
* @author wsq
* @date 2021/4/7
* 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
* 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
* 此外,你可以假设该网格的四条边均被水包围。
*
* 示例 1:
* 输入:grid = [
* ["1","1","1","1","0"],
* ["1","1","0","1","0"],
* ["1","1","0","0","0"],
* ["0","0","0","0","0"]
* ]
* 输出:1
*
* 链接:https://leetcode-cn.com/problems/number-of-islands
*/
public class NumIslands {
/**
* 构建方向数组
*/
private int[][] d = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int numIslands(char[][] grid) {
// 获取网格的维度的大小
int m = grid.length;
int n = grid[0].length;
// 存储1的位置
List<Integer> list = new ArrayList<>();
UnionFind unionFind = new UnionFind(n * m);
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == '1'){
list.add(i * n + j);
for(int[] t : d){
int x = i + t[0];
int y = j + t[1];
if(x < 0 || x >= m || y < 0 || y >= n){
continue;
}
if(grid[x][y] == '1'){
unionFind.union(i * n + j, x * n + y);
}
}
}
}
}
Set<Integer> set = new HashSet<>();
for(int e : list){
int rootE = unionFind.find(e);
set.add(rootE);
}
return set.size();
}
/**
* 并查集模板
* 实现带路径压缩的并查集
*/
class UnionFind{
private int[] parent;
public UnionFind(int n){
parent = new int[n];
for(int i = 0; i < n; i++){
parent[i] = i;
}
}
public void union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if(rootX == rootY){
return;
}
parent[rootX] = rootY;
}
public int find(int x){
if(parent[x] != x){
parent[x] = find(parent[x]);
}
return parent[x];
}
public boolean isConnected(int x, int y){
return find(x) == find(y);
}
}
}
200. 岛屿数量(并查集)
最新推荐文章于 2022-07-02 16:58:37 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)