200. Number of islands

Title description:

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 horizontal and / or vertical adjacent land connections.

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

Example 1:

Input:
11110
11010
11000
00000
Output: 1
Example 2:

Input:
11000
11000
00100
00011
Output: 3
Explanation: Each island can only be formed by connecting horizontally and / or vertically adjacent land.

thought:

Depth-first search: When [i, j] is '1', increase the number of islands, and then use depth-first search to set all grids near [i, j] to 1 to '0'

Code:

class Solution {
private:
    void dfs(vector<vector<char>>& grid,int i,int j){   //注意没有返回值用void,并且grid要引用
        int cols = grid[0].size();
        int rows = grid.size();
        grid[i][j] = '0';
        if(i-1>=0&&grid[i-1][j]=='1') dfs(grid,i-1,j);
        if(i+1<rows&&grid[i+1][j]=='1') dfs(grid,i+1,j);
        if(j-1>=0&&grid[i][j-1]=='1') dfs(grid,i,j-1);
        if(j+1<cols&&grid[i][j+1]=='1') dfs(grid,i,j+1);
    }
public:
    int numIslands(vector<vector<char>>& grid) {
        int count = 0;
        int rows = grid.size();
        if(rows == 0)   //注意判断输入为空的情况
            return count;
        int cols = grid[0].size();
        for(int i = 0;i < rows; i++)
            for(int j = 0;j < cols;j++){
                if(grid[i][j] == '1'){
                    count++;
                    dfs(grid,i,j);
                }
            }
        return count;
    }
};

 

Guess you like

Origin www.cnblogs.com/thefatcat/p/12743723.html