类别:BFS
难度:medium
题目描述
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.input;
0 0 0 0 1 0 0 0 0output:
0 0 0 0 1 0 0 0 0input:
0 0 0 0 1 0 1 1 1output:
0 0 0 0 1 0 1 2 1
算法分析
使用队列进行广度优先搜索。
(1)首先将所有的为0的位置放到队列中,并且为1的位置初始化为INT_MAX,
(2) 然后不断地取出队头的位置,
(3)对于队头位置的四个方向,判断从这个点出发到达其四个方向的相邻位置的距离是不是比相邻位置本身到达0的距离要小
(4)如果是的话,更新相邻位置的距离,并且将更新了距离的点的位置放到队列中
(5)当队列为空时,即得到了最终的结果。
代码实现
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>> ans(row, vector<int> (col, INT_MAX));
queue<pair<int,int>> que;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (matrix[i][j] == 0) {
que.push({i,j});
ans[i][j] = 0;
}
}
}
pair<int,int> temp;
int x, y, new_x, new_y;
while (!que.empty()) {
temp = que.front();
que.pop();
x = temp.first;
y = temp.second;
for (int i = 0; i < 4; ++i) {
new_x = x;
new_y = y;
switch (i) {
case 0:
new_x++;
break;
case 1:
new_x--;
break;
case 2:
new_y++;
break;
case 3:
new_y--;
break;
}
if (new_x >= 0 && new_x < row && new_y >= 0 && new_y < col) {
if (ans[new_x][new_y] > ans[x][y] + 1) {
ans[new_x][new_y] = ans[x][y] + 1;
que.push({new_x, new_y});
}
}
}
}
return ans;
}
};