0
点赞
收藏
分享

微信扫一扫

Leetcode1020:飞地的数量(广搜)

一葉_code 2022-02-12 阅读 87

You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.

A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.

Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j] is either 0 or 1.

思路:从矩阵最外圈出发,进行多源广度优先遍历,将遍历到的位置设为0,最后统计矩阵中1的个数即为答案

class Solution {
public:
    int numEnclaves(vector<vector<int>>& grid) {
        int m=grid.size(),n=grid[0].size();
        queue<pair<int,int>> qu;
        for(int i=0;i<m;i++){
            if(grid[i][0]){
                qu.emplace(i,0);
                grid[i][0]=0;
            }
            if(grid[i][n-1]){
                qu.emplace(i,n-1);
                grid[i][n-1]=0;
            }
        }
        for(int j=1;j<n-1;j++){
            if(grid[0][j]){
                qu.emplace(0,j);
                grid[0][j]=0;
            }
            if(grid[m-1][j]){
                qu.emplace(m-1,j);
                grid[m-1][j]=0;
            }
        }
        vector<pair<int,int>> dirs={{-1,0},{1,0},{0,-1},{0,1}};
        while(!qu.empty()){
            auto [x,y]=qu.front();qu.pop();
            for(auto& [dx,dy]:dirs){
                int nx=x+dx;
                int ny=y+dy;
                if(nx>0&&nx<m-1&&ny>0&&ny<n-1&&grid[nx][ny]){
                    qu.emplace(nx,ny);
                    grid[nx][ny]=0;
                }
            }
        }
        int ans=0;
        for(int i=1;i<m-1;i++){
            for(int j=1;j<n-1;j++){
                if(grid[i][j]) ans++;
            }
        }
        return ans;
    }
};

 

 

举报

相关推荐

0 条评论