1. 描述
给定一张栅格地图,求每个格子离最近的障碍物的距离。
Example 1:
Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
Example 2:
Input:
[[1,1,1],
[1,0,1],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]
2. 代码
class Solution {
public:
vector<vector<int> > updateMatrix(vector<vector<int> >& grid){
int rows = grid.size();
int cols = grid[0].size();
vector<vector<int> > dist(rows, vector<int>(cols, 0));
vector<vector<int> > mark(rows, vector<int>(cols, 0));
queue<pair<int, int> > Q;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(grid[i][j] == 0){
Q.push(make_pair(i, j));
mark[i][j] = 1;
}
}
}
const int dx[4] = { -1, 1, 0, 0 };
const int dy[4] = { 0, 0, -1, 1 };
while(!Q.empty()){
int x = Q.front().first;
int y = Q.front().second;
Q.pop();
for(int i = 0; i < 4; i++){
int newx = x + dx[i];
int newy = y + dy[i];
if(newx >= 0 && newx < rows &&
newy >= 0 && newy < cols && mark[newx][newy] == 0){
dist[newx][newy] = dist[x][y] + 1;
Q.push(make_pair(newx, newy));
mark[newx][newy] = 1;
}
}
}
return dist;
}
};