LeetCode : 200. Number of Islands 统计岛屿的数量

试题
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

代码
一个岛屿是无规则的,但是我们可以把当前的岛屿给mask掉,这样就不会影响下一个岛屿的统计。

class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        if(grid.length == 0 || grid[0].length == 0) return count;
        int row = grid.length;
        int col = grid[0].length;
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(grid[i][j] == '1'){
                    count++;
                    maskAll(grid, i, j, row, col);
                }
            }
        }
        return count;
    }
    
    public void maskAll(char[][] grid, int i, int j, int row, int col){
        if(grid[i][j] == '0'){
            return;
        }
        grid[i][j] = '0';
        
        if(i-1 >= 0){
            maskAll(grid, i-1, j, row, col);
        }
        if(i+1 < row){
            maskAll(grid, i+1, j, row, col);
        }
        if(j-1 >= 0){
            maskAll(grid, i, j-1, row, col);
        }
        if(j+1 < col){
            maskAll(grid, i, j+1, row, col);
        }
        return;
    }
}
发布了557 篇原创文章 · 获赞 500 · 访问量 153万+

猜你喜欢

转载自blog.csdn.net/qq_16234613/article/details/100621202