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 0Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1Output:
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.
这道题我先针对0把0周边的数设为1,后再将改为1的数加入队列中操作
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { //找最近的位置和0的距离
vector<vector<int>> empty;
if (matrix.empty())
return empty;
int r = matrix.size();
int c = matrix[0].size();
vector<vector<int>> result(r, vector<int>(c));
queue<int> rq;
queue<int> cq;
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
if (matrix[i][j] == 1) {
result[i][j] = INT_MAX;
}
}
}
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
if (matrix[i][j] == 0) {
set(result, i, j, rq, cq);
}
}
}
while (!rq.empty() && !cq.empty()) {
setcore(result, rq, cq);
}
return result;
}
void set(vector<vector<int>>& result, int i, int j, queue<int>& rq, queue<int>& cq) {
if (i > 0) {
if (result[i - 1][j] == INT_MAX) {
result[i - 1][j] = 1;
rq.push(i - 1);
cq.push(j);
}
}
if (i < result.size() - 1) {
if (result[i + 1][j] == INT_MAX) {
result[i + 1][j] = 1;
rq.push(i + 1);
cq.push(j);
}
}
if (j > 0) {
if (result[i][j - 1] == INT_MAX) {
result[i][j - 1] = 1;
rq.push(i);
cq.push(j - 1);
}
}
if (j < result[0].size() - 1) {
if (result[i][j + 1] == INT_MAX) {
result[i][j + 1] = 1;
rq.push(i);
cq.push(j + 1);
}
}
}
void setcore(vector<vector<int>>& result, queue<int>& rq, queue<int>& cq) {
int i = rq.front();
rq.pop();
int j = cq.front();
cq.pop();
if (i > 0) {
if (result[i - 1][j] == INT_MAX) {
rq.push(i - 1);
cq.push(j);
}
if (result[i - 1][j] == INT_MAX) {
result[i - 1][j] = result[i][j]+1;
}
else if (result[i - 1][j] != 0 && result[i - 1][j] != 1) {
result[i - 1][j] = min(result[i][j] + 1, result[i - 1][j]);
}
}
if (i < result.size() - 1) {
if ( result[i + 1][j] == INT_MAX) {
rq.push(i + 1);
cq.push(j);
}
if (result[i + 1][j] == INT_MAX) {
result[i + 1][j] = result[i][j]+1;
}
else if (result[i + 1][j] != 0 && result[i + 1][j] != 1) {
result[i + 1][j] = min(result[i][j] + 1, result[i + 1][j]);
}
}
if (j > 0) {
if ( result[i][j - 1]== INT_MAX) {
rq.push(i);
cq.push(j - 1);
}
if (result[i][j - 1] == INT_MAX) {
result[i][j - 1] = result[i][j]+1;
}
else if (result[i ][j-1] != 0 && result[i ][j-1] != 1) {
result[i][j - 1] = min(result[i][j] + 1, result[i][j - 1]);
}
}
if (j < result[0].size() - 1) {
if (result[i][j + 1] == INT_MAX) {
rq.push(i);
cq.push(j + 1);
}
if (result[i][j + 1] == INT_MAX) {
result[i][j + 1] = result[i][j]+1;
}
else if (result[i ][j+1] != 0 && result[i ][j+1] != 1) {
result[i ][j+1] = min(result[i][j] + 1, result[i][j + 1]);
}
}
}
};
代码较混乱,后来想了化简的方法,可以不用分两种进行set,先留下坑,下次填