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:
11110110101100000000Answer: 1
Example 2:
11000110000010000011Answer: 3
思路:找到1后将其本身与相邻的1全部变为0,number加一,代码:
public int numIslands(char[][] grid) { int m=grid.length; int n=grid[0].length; int num=0; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j]=='0') continue; num++; search(grid,i,j); } } return num; } public void search(char[][] grid,int i,int j){ if(i<0||i>=grid.length||j<0||j>=grid[0].length) return; if(grid[i][j]=='1'){ grid[i][j]='0'; search(grid,i+1,j); search(grid,i-1,j); search(grid,i,j+1); search(grid,i,j-1); } }
