LeetCode:M-200. Number of Islands

LeetCode链接


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、遍历数组,遇见1后,遍得到一个新的岛屿,进行dfs遍历,对于遍历过的位置,设置为0

这样就将遍历过的岛屿设置为0了,剩下的都是别的独立的岛屿

2、继续遍历重复上面操作,得到最后岛屿数


class Solution {
    public int numIslands(char[][] grid) {
        if(grid==null || grid.length==0) return 0;
        
        int m = grid.length;
        int n = grid[0].length;
        int cnt=0;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j]=='1'){
                    dfs(grid, i, j);
                    cnt++;
                }               
            }
        }
        
        return cnt;
    }
    void dfs(char[][] grid, int i, int j){
        if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j]=='0')
            return;
        
        grid[i][j]='0';
        dfs(grid, i-1, j);
        dfs(grid, i+1, j);
        dfs(grid, i, j-1);
        dfs(grid, i, j+1);
    }
}


猜你喜欢

转载自blog.csdn.net/iyangdi/article/details/77963641