题解 | #岛屿数量-简化风BFS#

岛屿数量

http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e

public:
    vector<vector<char> > grid;
    
    bool BFS(int i,int j)
    {
        if(grid[i][j]=='0') 
            return false;
        
        queue<pair<int,int> > Q;
        
        Q.push({i,j});
        
        while(!Q.empty())
        {
            auto tmp = Q.front();
            
            Q.pop();
            
            int x = tmp.first;
            int y = tmp.second;
            
            //BFS(x,y);
            grid[x][y]='0';
            
            if(x+1<=H-1&&grid[x+1][y]=='1')
                Q.push({x+1,y});
            if(x-1>=0&&grid[x-1][y]=='1')
                Q.push({x-1,y});
            if(y+1<=W-1&&grid[x][y+1]=='1')
                Q.push({x,y+1});
            if(y-1>=0&&grid[x][y-1]=='1')
                Q.push({x,y-1});
        }
        
        return true;
    }
    
    int H;
    int W;
    
    int solve(vector<vector<char> >& grid_) {
        
        grid = grid_;
        
        H = grid.size();
        W = grid[0].size();
        
        int res = 0;
        
        for(int i=0;i<H;i++)
            for(int j=0;j<W;j++)
                if(BFS(i,j)) res++;
        
        return res;
        
    }
};
全部评论

相关推荐

杨柳哥:这不是普通人,那这个钱的是天才
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务