xinyu04

导航

LeetCode 542 01 Matrix 多源BFS

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Solution

给定一个 \(01\)矩阵,要求每个点离最近的 \(0\) 的距离(曼哈顿距离)。虽然是 \(DP\) 的标签,但其实应该是 \(BFS\) 来解决。我们先将所有 \(0\) 加入队列,然后每次 \(pop\) 出一个元素,将其相邻元素加入队列。加入队列之前必须判断是否合法以及是否是没有访问过的元素,因此为了方便起见,我们将所有距离初始化为 \(-1\),然后每次将 \(-1\) 的点加入队列。

点击查看代码
class Solution {
private:
    int dir[4][2]={
        0,1,
        1,0,
        -1,0,
        0,-1
    };
    bool check(int i,int j,int n, int m){
        if(i<0||j<0||i>=n||j>=m)return false;
        return true;
    }
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int n = mat.size(), m = mat[0].size();
        vector<vector<int>> dis(n, vector<int>(m,-1));
        queue<pair<int,int>> q;
        
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(mat[i][j]==0){
                    q.push(pair(i,j));
                    dis[i][j] = 0;
                }
            }
        }
        
        while(!q.empty()){
            pair<int,int> cur = q.front();
            q.pop();
            for(int i=0;i<4;i++){
                int nx = cur.first + dir[i][0];
                int ny = cur.second + dir[i][1];
                if(check(nx,ny,n,m)&&dis[nx][ny]==-1){
                    q.push(pair(nx,ny));
                    dis[nx][ny] = dis[cur.first][cur.second]+1;
                }
            }
        }
        return dis;
        
    }
};

posted on 2022-05-20 05:01  Blackzxy  阅读(20)  评论(0编辑  收藏  举报