LeetCode: 200. Number of Islands count the 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

Code
an island is irregular, but we can present to mask off the island, so it will not affect the next island of statistics.

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;
    }
}
Published 557 original articles · won praise 500 · Views 1.53 million +

Guess you like

Origin blog.csdn.net/qq_16234613/article/details/100621202