200. Number of Islands 200.岛屿数(可以形状一样)

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: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

思路:不知道递归过程中怎么数数,应该在主函数里面写啊。

class Solution {
    public int numIslands(char[][] grid) {
        //cc
        if (grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        
        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') {
                    dfs(grid, i, j);
                    count++;
                }
            }
        }
        
        return count;
    }
    
    //返回面积
    public int dfs(char[][] grid, int x, int y) {
        //标记
        if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 
           grid[x][y] == '1') {             
                grid[x][y] = '0';
                              
                dfs(grid, x - 1, y); 
                dfs(grid, x + 1, y);
                dfs(grid, x, y - 1);
                dfs(grid, x, y + 1);         
        }
        
        return 0;
    }
}
View Code

 



posted @ 2020-08-27 10:24  苗妙苗  阅读(126)  评论(0编辑  收藏  举报