【leetcode 广度优先搜索 C++】1162. As Far from Land as Possible

1162. As Far from Land as Possible

在这里插入图片描述

class Solution {
    
    
public:
    int maxDistance(vector<vector<int>>& grid) {
    
    
        queue<pair<int, int>> Q;
        int H = grid.size();
        int W = grid[0].size();
        int ans = -1;
        int y, x;
        vector<vector<bool> > visited(H, vector<bool>(W, false));
        for(int ii = 0; ii < H; ii++) {
    
    
            for(int jj = 0; jj < W; jj++) {
    
    
                if(grid[ii][jj]) {
    
    
                    Q.push({
    
    ii, jj});
                    visited[ii][jj] = true;
                }
            }
        }
        if(Q.size() == H*W || Q.size() == 0) return ans;
        while(!Q.empty()) {
    
    
            int len = Q.size();
            for(int ii = 0; ii < len; ii++) {
    
    
                auto A = Q.front();
                Q.pop();
                y = A.first - 1, x = A.second;
                if(y >= 0 && y < H && !visited[y][x]) {
    
    
                    visited[y][x] = true;
                    Q.push({
    
    y, x});
                }
                y = A.first + 1, x = A.second;
                if(y >= 0 && y < H && !visited[y][x]) {
    
    
                    visited[y][x] = true;
                    Q.push({
    
    y, x});
                }
                y = A.first, x = A.second - 1;
                if(x >= 0 && x < W && !visited[y][x]) {
    
    
                    visited[y][x] = true;
                    Q.push({
    
    y, x});
                }
                y = A.first, x = A.second + 1;
                if(x >= 0 && x < W && !visited[y][x]) {
    
    
                    visited[y][x] = true;
                    Q.push({
    
    y, x});
                }
            }
            ans++;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/113872539