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
题目要求,1表示小岛,0表示海,找出所有的小岛;一开始还没有思路,看了别人的博客说用dfs一下子想清楚了,用一个嵌套循环对每个点进行判断,如果当前值为1的话,那么调用bfs方法,将它连接到部分的1全部置为0, 这样在嵌套的过程中记录出现1的个数,在bfs会把它相邻的1全部去掉,所以不会出现多加或者少加的情况。
public static void main(String[] args) {
NumIslands is = new NumIslands();
char[][] grid = {
{'1','1','1','1','0'},
{'1','1','0','1','0'},
{'1','1','0','0','0'},
{'0','0','0','0','0'}
};
System.out.println(is.numIslands(grid));
}
public int numIslands(char[][] grid) {
int count = 0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j] == '1'){
//System.out.println("find 1");
count++;
}
bfs(i, j, grid);
}
}
return count;
}
public void bfs(int i, int j, char[][] grid){
if(grid[i][j] == '1'){
grid[i][j] = '0';
if(i>0)
bfs(i-1, j, grid);
if(i<grid.length-1)
bfs(i+1, j, grid);
if(j>0)
bfs(i, j-1,grid);
if(j<grid[0].length-1)
bfs(i, j+1, grid);
}else return;
}