Given a matrix of 0s and 1s, find the distance of each element to the nearest 0.
The distance between two adjacent elements 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:
1. The number of elements of a given matrix should not exceed 10000.
2. At least one element in the given matrix is 0.
3. Elements in a matrix are adjacent only in four directions: up, down, left, right.
See: https://leetcode.com/problems/01-matrix/description/
C++:
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> res(m, vector<int>(n, INT_MAX - 1)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { res[i][j] = 0; } else { if (i > 0) { res[i][j] = min(res[i][j], res[i - 1][j] + 1); } if (j > 0) { res[i][j] = min(res[i][j], res[i][j - 1] + 1); } } } } for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { if (res[i][j] != 0 && res[i][j] != 1) { if (i < m - 1) { res[i][j] = min(res[i][j], res[i + 1][j] + 1); } if (j < n - 1) { res[i][j] = min(res[i][j], res[i][j + 1] + 1); } } } } return res; } };
Reference: https://www.cnblogs.com/grandyang/p/6602288.html