Number of Islands

Posted illfuckingkyzb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Number of Islands相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    
    int numIslands(vector<vector<char>>& grid) {
 if (grid.empty() || grid[0].empty()) return 0;
        int count=0;
       
        int m = grid.size(), n = grid[0].size();
        vector<vector<bool>> visit(m, vector<bool>(n, false));        for(int  i=0;i<m;i++){

            for(int j=0;j<n;j++){
                if(grid[i][j]==1&&!visit[i][j]){
                
                    dfs(grid,visit,i,j);
              ++count;
                }
            }}
        return count;
    }
    void dfs(vector<vector<char>>& grid, vector<vector<bool>> &visit,int x,int y){
        if (x < 0 || x >= grid.size()) return;
        if (y < 0 || y >= grid[0].size()) return;
        if (grid[x][y] != 1 || visit[x][y]) return;
        visit[x][y] = true;
        dfs(grid, visit, x - 1, y);
        dfs(grid, visit, x + 1, y);
         dfs(grid, visit, x, y - 1);
         dfs(grid, visit, x, y + 1);
    }
};

 

以上是关于Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章

leetcode200. Number of Islands

200. Number of Islands

Number of Islands

LeetCode Number of Islands II

Number of Islands

200. Number of Islands