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
首先将所有的 \(dis\) 令成 \(-1\),然后把所有 \(0\) 的点 \(push\) 到队列里面,每次更新 \(dis[i][j]=-1\) 的点
点击查看代码
class Solution {
private:
int dir[4][2] = {0,1, 1,0, 0,-1, -1,0};
bool check(int x,int y,int r, int c){
if(x<0||y<0||x>=r||y>=c)return false;
return true;
}
queue<vector<int>> q;
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int r = mat.size(), c = mat[0].size();
vector<vector<int>> dis(r, vector<int>(c,-1));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(mat[i][j]==0){
dis[i][j]=0;q.push({i,j});
}
}
}
while(!q.empty()){
auto f = q.front();q.pop();
int x = f[0], y = f[1];
for(int i=0;i<4;i++){
int nx = x+dir[i][0], ny = y+dir[i][1];
if(check(nx,ny,r,c)&&dis[nx][ny]==-1){
dis[nx][ny] = dis[x][y]+1;
q.push({nx,ny});
}
}
}
return dis;
}
};