Number of Islands
重点题目
Input:
11110
11010
11000
00000
Output: 1Input:
11000
11000
00100
00011
Output: 3Last updated
重点题目
Input:
11110
11010
11000
00000
Output: 1Input:
11000
11000
00100
00011
Output: 3Last updated
class Solution {
public int numIslands(char[][] grid) {
//BFS
if(grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
int res = 0;
boolean[][] visited = new boolean[grid.length][grid[0].length];
for(int i = 0; i < grid.length;i++){
for(int j = 0; j < grid[0].length;j++){
if(grid[i][j] == '1' && !visited[i][j]){
res++;
bfs(grid,visited,i,j);
}
}
}
return res;
}
public void bfs(char[][] grid,boolean[][] visited, int x,int y){
int[] dx = {1,0,-1,0};
int[] dy = {0,1,0,-1};
Queue<Integer> xQueue = new LinkedList<>();
Queue<Integer> yQueue = new LinkedList<>();
xQueue.offer(x);
yQueue.offer(y);
while(!xQueue.isEmpty()){
int X = xQueue.poll(), Y = yQueue.poll();
for(int i = 0; i < 4;i++){
int cx = X+ dx[i];
int cy = Y + dy[i];
if(inBound(grid, cx,cy) && grid[cx][cy] == '1' && !visited[cx][cy]){
visited[cx][cy] = true;
xQueue.offer(cx);
yQueue.offer(cy);
}
}
}
}
public boolean inBound(char[][] grid, int x, int y){
return x >=0 && x < grid.length && y >=0 && y < grid[0].length;
}
}