題目描述
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
[[0,0,0],
[0,1,0],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
Example 2:
Input:
[[0,0,0],
[0,1,0],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.
思路
bfs,從零步的位置開始拓展。
代碼
class Solution {
public:
vector<int> dirs {1, 0, -1, 0, 1};
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
vector<vector<int>> res(n, vector<int>(m, INT_MAX));
queue<pair<int, int>> que;
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) {
if (matrix[i][j] == 0) {
res[i][j] = 0;
que.push({i, j});
}
}
}
int step = 1;
while(!que.empty()) {
int size = que.size();
while(size--) {
pair<int, int> tmp = que.front();
que.pop();
int x = tmp.first;
int y = tmp.second;
for (int i=0; i<4; ++i) {
int nx = x + dirs[i];
int ny = y + dirs[i+1];
if (nx <0 || nx >= n || ny < 0 || ny >= m) continue;
if (res[nx][ny] <= res[x][y] + 1) continue;
res[nx][ny] = res[x][y] + 1;
que.push({nx, ny});
}
}
}
return res;
}
};