【BFS】LeetCode 200. 岛屿数量
题目链接
思路
BFS在图上的简单应用
代码
class Solution {
private void bfs(int i, int j, boolean[][] visit, char[][] grid) {
int[] dx = new int[]{1, 0, -1, 0};
int[] dy = new int[]{0, 1, 0, -1};
Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
queue.add(new Pair<>(i, j));
visit[i][j] = true;
while(!queue.isEmpty()){
int x = queue.peek().getKey();
int y = queue.poll().getValue();
for(int k = 0; k < 4; k++){
int nextX = x + dx[k];
int nextY = y + dy[k];
if(0 <= nextX && nextX < grid.length && 0 <= nextY && nextY < grid[0].length
&& grid[nextX][nextY] == '1' && !visit[nextX][nextY]){
queue.add(new Pair<>(nextX, nextY));
visit[nextX][nextY] = true;
}
}
}
}
public int numIslands(char[][] grid) {
boolean[][] visit = new boolean[grid.length][grid[0].length];
int result = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[i].length; j++){
if(grid[i][j] == '1' && !visit[i][j]){
bfs(i, j, visit, grid);
result++;
}
}
}
return result;
}
}