【Like】200. Number of islands

Subject : Give you a two-dimensional grid composed of '1' (land) and '0' (water). Please count the number of islands in the grid.

Islands are always surrounded by water, and each island can only be formed by connecting adjacent land in horizontal and/or vertical directions.

In addition, you can assume that all four sides of the grid are surrounded by water.

Example 1:

enter:

11110
11010
11000
00000

Output: 1

Example 2:

enter:

11000
11000
00100
00011

Output: 3
Explanation: Each island can only be formed by connecting adjacent land in the horizontal and/or vertical direction.

Answer :

class Solution {
    
    
    public int numIslands(char[][] grid) {
    
    
        int islandNum = 0;
        for(int i = 0; i < grid.length; i++){
    
    
            for(int j = 0; j < grid[0].length; j++){
    
    
                if(grid[i][j] == '1'){
    
    
                    infect(grid, i, j);
                    islandNum++;
                }
            }
        }
        return islandNum;
    }
    //感染函数
    public void infect(char[][] grid, int i, int j){
    
    
        if(i < 0 || i >= grid.length ||
           j < 0 || j >= grid[0].length || grid[i][j] != '1'){
    
    
            return;
        }
        grid[i][j] = '2';
        infect(grid, i + 1, j);
        infect(grid, i - 1, j);
        infect(grid, i, j + 1);
        infect(grid, i, j - 1);
    }
}

Guess you like

Origin blog.csdn.net/weixin_44485744/article/details/105657734