542. 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 0
Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1
Output:
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的最近距离,之所以需要遍历两遍是因为第一次假设某些点周围都是1,那就会导致该点的值为无穷大,再倒着遍历的时候他的周边距离变成已知数,所以会更新当前节点的最小值。
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int row=matrix.size(),col=matrix[0].size(); vector<vector<int> >dp(row,vector<int>(col,INT_MAX)); for(int times=0;times<=1;times++) for(int i=times?row-1:0;times?i>=0:i<row;times?i--:i++) for(int j=times?col-1:0;times?j>=0:j<col;times?j--:j++) if(!matrix[i][j]){ dp[i][j]=0; } else if(dp[i][j]){ if(i&&dp[i-1][j]!=INT_MAX&&dp[i][j]>dp[i-1][j]+1) dp[i][j]=dp[i-1][j]+1; if(j+1<col&&dp[i][j+1]!=INT_MAX&&dp[i][j]>dp[i][j+1]+1) dp[i][j]=dp[i][j+1]+1; if(i+1<row&&dp[i+1][j]!=INT_MAX&&dp[i][j]>dp[i+1][j]+1) dp[i][j]=dp[i+1][j]+1; if(j&&dp[i][j-1]!=INT_MAX&&dp[i][j]>dp[i][j-1]+1) dp[i][j]=dp[i][j-1]+1; } return dp; } };