01 Matrix
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.
开始用dfs,runtime error ,是后面的点可能依赖前面点的结果,觉得dfs是可行的,只是自己写的代码有问题,后来用bfs,还是擅长bfs,用dfs实现的可以交流一下。。。。QAQ..
代码:
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
int rows=matrix.size();
int cols=matrix[0].size();
vector<vector<int> > ans (rows,vector<int>(cols,0));
queue<pair<int,int>>que;
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
if (matrix[i][j]==0)
que.push(make_pair(i,j));
}
}
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};
while (!que.empty())
{
int posy=que.front().first;
int posx=que.front().second;
for (int k=0; k<4; k++)
{
int tempy=posy+dy[k];
int tempx=posx+dx[k];
if (tempy<0||tempx<0||tempy>=rows||tempx>=cols)
{
continue;
}
if (matrix[tempy][tempx]==0||ans[tempy][tempx]) continue;
ans[tempy][tempx]=ans[posy][posx]+1;
que.push(make_pair(tempy,tempx));
}
que.pop();
}
return ans;
}
};