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:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

  200. Number of Islands 随笔

用DFS,遇到1就ans++,然后搜索所有他的1邻居直到搜不到了,这时代表有一个island,

接下来继续搜索,原理同上

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

注意m,n,i,j的含义

 

ref:https://www.youtube.com/watch?v=XSmgFKe-XYU

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄