


java
package siyangyuan;
import java.util.LinkedList;
import java.util.Queue;
/**
* Class Name :daoyuwenti
* Package :siyangyuan
* Description:
*
* @Author: Mr.chunxugao
* Create: 2026-03-15- 18:43
* @Version:v1.0
*/
public class daoyuwenti {
public static void main(String[] args) {
char[][] grid = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};
System.out.println(numIslands(grid)); // 输出:3
}
//求岛屿的数量
private static int numIslands(char[][] grid) {
if (grid==null) return 0;
//求行数
int row= grid.length;
int cow=grid[0].length;//求列数
int islandcount=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < cow; j++) {
//要注意这里的字符是单引号
if (grid[i][j]=='1'){
islandcount++;
// 3. BFS:把这座岛全部淹没(变成0)
BFS(grid,i,j,row,cow);
}
}
}
return islandcount;
}
//bfs淹没陆地
private static void BFS(char[][] grid, int i, int j, int row, int cow) {
//bfs需要队列,保存陆地的坐标
Queue<int[]> queue= new LinkedList<>();
//对于当前的的第一个元素,直接入队,并且淹没
queue.offer(new int[]{i,j});
grid[i][j]='0';
// 上下左右四个方向(固定写法)
int[][] dris= {{-1,0},{1,0},{0,-1},{0,1}};
// BFS循环:和层序遍历完全一样!
while (!queue.isEmpty()){
//出队。并且进行淹没
int[] cur=queue.poll();
int x=cur[0];
int y=cur[1];
//看上下左右有没有陆地进行合并淹没
for(int[] dir:dris){
int newx=x+dir[0];
int newy=y+dir[1];
//对于这种上下左右的,我们进行判断之后,入队,继续判断,然后符合条件的淹没
if(newx>=0&&newx<row&&newy>=0&&newy<cow&&grid[newx][newy]=='1'){
queue.offer(new int[]{newx,newy});
grid[newx][newy]='0';
}
}
}
}
}


