package bfs;
import java.util.LinkedList;
import java.util.Queue;
//leetcode 200. 岛屿数量
public class Land {
public int numIslands(char[][] grid) {
int sum = 0;
//非法情况
if (grid == null || grid.length == 0) {
return sum;
}
//数组行数
int r = grid.length;
//数组列数
int c = grid[0].length;
//遍历数组
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
//bfs套路之一:队列
Queue<Integer> queue = new LinkedList<>();
//bfs套路之二:初始条件加入到队列中,并更新岛屿数量,更新访问过的节点
if (grid[i][j] == '1' ) {
sum ++;
queue.add(i * c + j);
grid[i][j] = 0;
}
//队列不为空,一直遍历
while (!queue.isEmpty()) {
//取队首元素,准备访问和它相邻的节点
int rem = queue.remove();
//计算队首数值具体的坐标x,y
int x = rem / c;
int y = rem % c;
//注意每次的边界条件
// 访问这个节点右边的位置
//如果符合条件,那么将它加入到队列中,更新访问过的节点
//为什么这次不用更新岛屿数量(sum):
// 在while里访问的节点都是和上次队首位置相邻的节点,说明是同一个岛屿
if (x + 1 < r && grid[x + 1][y] == '1') {
queue.add((x + 1) * c + y);
grid[x + 1][y] = 0;
}
//访问这个节点左边的位置
if (x - 1 >= 0 && grid[x - 1][y] == '1') {
queue.add((x - 1) * c + y);
grid[x - 1][y] = 0;
}
//下面
if (y + 1 < c && grid[x][y + 1] == '1') {
queue.add(x * c + y + 1);
grid[x][y + 1] = 0;
}
//上面
if (y - 1 >= 0 && grid[x][y - 1] == '1') {
queue.add(x * c + y - 1);
grid[x][y - 1] = 0;
}
}
}
}
return sum;
}
//测试
public static void main(String[] args) {
char[][] chars = {
{'1','1','0','1','0'},
{'1','1','0','1','0'},
{'1','1','0','0','1'},
{'0','0','1','0','1'}
};
Land land = new Land();
System.out.println(land.numIslands(chars));
}
}
bfs岛屿数量(LeetCode200. 岛屿数量)含注释
最新推荐文章于 2024-04-05 14:43:20 发布