题目链接: 力扣
题目描述
给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例1:红色标志的为一个岛屿
示例2:红色、黄色、蓝色各表示不同的岛屿
题目分析
广度优先搜索(BFS)是一种遍历或搜索数据结构(如树或图)的算法。
· BFS 在树中执行层序遍历。
· BFS 遍历图。例如,我们可以使用 BFS 找到从起始结点到目标结点的路径,特别是最短路径。
- 为了求出岛屿的数量,我们可以扫描整个二维网格;
- 如果一个位置为 1,开始进行广度优先搜索,并在队列中记录该位置;
- 在广度优先搜索的过程中,每个搜索到的 1 都会被重新标记为 0;
- 最终岛屿的数量就是我们进行广度优先搜索的次数。
用来记录位置的队列该如何设计呢?
思考:要记录 '1'(陆地)位置信息,主要就是要知道在二维网络中 x,y 坐标,故而在这里选用了 LandPosition 对象整合坐标信息。
代码实现
/**
* BFS - 广度优先搜索
*/
public int numIslands(char[][] grid) {
int landNum = 0;
if (grid == null || grid.length == 0) {
return landNum;
}
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
// 遇到'1'(陆地),进行广度优先搜索
if (grid[i][j] == '1') {
landNum++;
grid[i][j] = '0';
// 队列,FIFO,存储 '1'(陆地) 的位置信息
Queue<LandPosition> queue = new LinkedList();
queue.add(new LandPosition(i, j));
while (!queue.isEmpty()) {
// 查看当前岛屿上下左右的元素
LandPosition currLand = queue.poll();
if (currLand.x - 1 >= 0 && grid[currLand.x - 1][currLand.y] == '1') {
queue.add(new LandPosition(currLand.x - 1, currLand.y));
grid[currLand.x - 1][currLand.y] = '0';
}
if (currLand.x + 1 < grid.length && grid[currLand.x + 1][currLand.y] == '1') {
queue.add(new LandPosition(currLand.x + 1, currLand.y));
grid[currLand.x + 1][currLand.y] = '0';
}
if (currLand.y - 1 >= 0 && grid[currLand.x][currLand.y - 1] == '1') {
queue.add(new LandPosition(currLand.x, currLand.y - 1));
grid[currLand.x][currLand.y - 1] = '0';
}
if (currLand.y + 1 < grid[0].length && grid[currLand.x][currLand.y + 1] == '1') {
queue.add(new LandPosition(currLand.x, currLand.y + 1));
grid[currLand.x][currLand.y + 1] = '0';
}
}
}
}
}
System.out.println("岛屿数量:" + landNum);
return landNum;
}
/**
* 记录位置信息
*/
public class LandPosition {
int x;
int y;
public LandPosition() {
}
public LandPosition(int x, int y) {
this.x = x;
this.y = y;
}
}
感谢各位看官到这里,不如点个关注吧~~