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点的距离的值,这样判断的话离该点比较远的点的值也会累加作用到这个点,是一种非常巧妙的解题方式,第一遍遍历完成之后还要再反向做一次遍历,这是因为第一遍遍历的时候只能通过前面的点影响后面的点,后面的点不能影响前面的点,因此需要再逆向遍历一次使得后面的点可以影响前面的点,是一种非常强大的解法!算法的时间复杂度是O(n * n).
下面贴上程序:
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int height = matrix.size();
int width = matrix[0].szie();
vector<vector<int>> vec(height, vector<int>
(width, INT_MAX));
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (matrix[i][j] == 0) {
vec[i][j] = 0;
} else {
//look up
if (i > 0 && vec[i - 1][j] != INT_MAX &&
vec[i][j] > vec[i - 1][j] + 1)
vec[i][j] = vec[i - 1][j] + 1;
//look left
if (j > 0 && vec[i][j - 1] != INT_MAX &&
vec[i][j] > vec[i][j - 1] + 1)
vec[i][j] = vec[i][j - 1] + 1;
//look down
if (i < height - 1 && vec[i + 1][j] !=
INT_MAX && vec[i][j] > vec[i + 1][j] + 1)
vec[i][j] = vec[i + 1][j] + 1;
//look right
if (j < width - 1 && vec[i][j + 1] !=
INT_MAX && vec[i][j] > vec[i][j + 1] + 1)
vec[i][j] = vec[i][j + 1] + 1;
}
}
}
for (int i = height - 1; i >= 0; i--) {
for (int j = qidth - 1; j >= 0; j--) {
if (matrix[i][j] == 0) {
vec[i][j] = 0;
} else {
//look up
if (i > 0 && vec[i - 1][j] != INT_MAX &&
vec[i][j] > vec[i - 1][j] + 1)
vec[i][j] = vec[i - 1][j] + 1;
//look left
if (j > 0 && vec[i][j - 1] != INT_MAX &&
vec[i][j] > vec[i][j - 1] + 1)
vec[i][j] = vec[i][j - 1] + 1;
//look down
if (i < height - 1 && vec[i + 1][j] !=
INT_MAX && vec[i][j] > vec[i + 1][j] + 1)
vec[i][j] = vec[i + 1][j] + 1;
//look right
if (j < width - 1 && vec[i][j + 1] !=
INT_MAX && vec[i][j] > vec[i][j + 1] + 1)
vec[i][j] = vec[i][j + 1] + 1;
}
}
}
return vec;
}
};