题目
Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
题目解析
输入为一个二维矩阵,矩阵由 0 1构成,0为海水,1为陆地,相连的 1 组成岛屿,相连是指 上 下 左 右 四个点相连,斜边不考虑,输出岛屿的数量。
实现
//coding = java
public class Solution{
//布尔数组默认值为 false
boolean[][] visited = new boolean[grid.length][grid[0].length];
public int numIslands(char[][] grid){
if(grid == null || grid.length==0 || grid[0].length==0){
return 0;
}
int num =0;
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]){
num++;
bfs(grid,visited,i,j);
}
}
}
return num;
}
public void bfs(char[][] grid,boolean[][] visited,int i,int j){
if(i>=0 && i<grid.length && j>=0 && j<grid[0].length && !visited[i][j] && grid[i][j]=='1'){
visited[i][j]=true;
bfs(grid,visited,i,j-1);
bfs(grid,visited,i-1,j);
bfs(grid,visited,i,j+1);
bfs(grid,visited,i+1,j);
}
}
}