给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例1:
输入:
0 0 0
0 1 0
0 0 0
输出:
0 0 0
0 1 0
0 0 0
示例2:
输入:
0 0 0
0 1 0
1 1 1
输出:
0 0 0
0 1 0
1 2 1
注意:
1、给定矩阵的元素个数不超过 10000。
2、给定矩阵中至少有一个元素是 0。
3、矩阵中的元素只在四个方向上相邻: 上、下、左、右。
思路:
1、遍历所有点,数值为零压入队列,进行广度优先搜索,非零点被赋值为最大值。
2、零点的广度优先搜索:以每个零点为根节点进行广度优先搜索,如果新节点值比旧节点值大,则matrix[nrow][ncol]=matrix[row][col]+1,并压入新节点的下标。
代码:
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
queue<pair<int,int>> q;
int r=matrix.size();
int c=matrix[0].size();
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(matrix[i][j]==0)
{
q.push({i,j});
}
else
{
matrix[i][j]=INT_MAX;
}
}
}
while(!q.empty())
{
auto value = q.front();
q.pop();
int row = value.first;
int col = value.second;
int movex[] = {0,0,-1,1};
int movey[] = {1,-1,0,0};
for(int i=0;i<4;i++)
{
int nrow = row + movex[i];
int ncol = col + movey[i];
if(nrow>=0&&nrow<r&&ncol>=0&&ncol<c&&matrix[nrow][ncol]>matrix[row][col])
{
matrix[nrow][ncol]=matrix[row][col]+1;
q.push({nrow,ncol});
}
}
}
return matrix;
}
};