- 01 矩阵
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:mat = [[0,0,0],[0,1,0],[0,0,0]]
输出:[[0,0,0],[0,1,0],[0,0,0]]
示例 2:
输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
输出:[[0,0,0],[0,1,0],[1,2,1]]
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
mat 中至少有一个 0
题解
把所有为0的位置储存下来反向遍历。
AC代码
class Solution {
public:
struct Node
{
int x,y,dp;
};
queue<Node>q;
vector<vector<int>>res;
int xx[4]={0,0,-1,1};
int yy[4]={-1,1,0,0};
void bfs(vector<vector<int>>& matrix)
{
Node t;
for(int i=0;i<matrix.size();i++)
{
vector<int>path;
for(int j=0;j<matrix[i].size();j++)
{
path.push_back(-1);
if(matrix[i][j]==0)
{
t.x=i,t.y=j,t.dp=0;
q.push(t);
}
}
res.push_back(path);
}
while(!q.empty())
{
t=q.front();
q.pop();
if(res[t.x][t.y]==-1)
res[t.x][t.y]=t.dp;
for(int i=0;i<4;i++)
{
Node w;
w.x=t.x+xx[i];
w.y=t.y+yy[i];
w.dp=t.dp+1;
if(w.x<0||w.x>=matrix.size()||w.y<0||w.y>=matrix[0].size())continue;
if(res[w.x][w.y]!=-1)continue;
if(matrix[w.x][w.y]==0)continue;
res[w.x][w.y]=w.dp;
q.push(w);
}
}
}
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
bfs(matrix);
return res;
}
};