lc-200


/**
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0
's (water), return 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
 

 
 Constraints: 

 
 m == grid.length 
 n == grid[i].length 
 1 <= m, n <= 300 
 grid[i][j] is '0' or '1'. 
 
 Related Topics深度优先搜索 | 广度优先搜索 | 并查集 | 数组 | 矩阵 

 👍 1899, 👎 0 

*/	
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int numIslands(char[][] grid) {
        int cnt = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    cnt++;
                    scaleOut(grid, i, j);
                }
            }
        }

        return cnt;
    }

    private void scaleOut(char[][] grid, int r, int c) {
        if (grid[r][c] == '0') {
            return;
        }

        grid[r][c] = '0';

        if (r < grid.length - 1) {
            scaleOut(grid, r + 1, c);
        }


        if (c < grid[0].length - 1) {
            scaleOut(grid, r, c + 1);
        }


        if (r > 0) {
            scaleOut(grid, r - 1, c);
        }


        if (c > 0) {
            scaleOut(grid, r, c - 1);
        }

    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !