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:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
适用dfs
1 class Solution {//dfs my 2 public int numIslands(char[][] grid) { 3 if(null==grid||0==grid.length){ 4 return 0; 5 } 6 int row =grid.length; 7 int col = grid[0].length; 8 int re = 0; 9 boolean[][] visited=new boolean[row][col];//判断的是否访问过 10 for(int i=0;i<row;i++){ 11 for(int j=0;j<col;j++){ 12 if('1'==grid[i][j]&&!visited[i][j]){//为1且没有访问过,表示是另一个岛 13 dfs(grid,visited,i,j); 14 re++; 15 } 16 } 17 } 18 return re; 19 } 20 private void dfs(char[][] grid,boolean[][] visited,int i,int j){ 21 if(i<0||j<0||i>=grid.length||j>=grid[0].length){ 22 return; 23 } 24 if('1'==grid[i][j]&&!visited[i][j]){ 25 visited[i][j]=true; 26 dfs(grid,visited,i+1,j); 27 dfs(grid,visited,i-1,j); 28 dfs(grid,visited,i,j+1); 29 dfs(grid,visited,i,j-1); 30 } 31 } 32 }