200. 岛屿的个数/C++

在这里插入图片描述

class Solution {
private:
    int d[4][2]= {{0,1}, {0, -1}, {1,0},{-1, 0}};
    int row,col;
    vector<vector<bool>> visited;
    
    bool inArea(int x,int y){
        return x>=0 && x<row && y>=0 && y<col;
    }
    
    void dfs(vector<vector<char>>& grid, int x, int y){
        visited[x][y] = true;
        
        for(int i=0;i<4;++i){
            int newX = x + d[i][0];
            int newY = y + d[i][1];
            
            if(inArea(newX,newY) && !visited[newX][newY] && grid[newX][newY]=='1')
                dfs(grid,newX,newY);
        }
        return;
    }
public:
    int numIslands(vector<vector<char>>& grid) {
        row=grid.size();
        if(row==0)
            return 0;
        
        col=grid[0].size();
        if(col==0)
            return 0;
        
        for(int i=0;i<row;++i)
            visited.push_back(vector<bool>(col,false));
        
        int res=0;
        for(int i=0;i<row;++i)
            for(int j=0;j<col;++j)
                if(grid[i][j]=='1' && !visited[i][j]){
                	//每次dfs都可以遍历一个岛屿
                    dfs(grid,i,j);
                    ++res;
                }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/Zolewit/article/details/89668292