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.
Subscribe to see which companies asked this question.
Solution:
Tips:
iterator matrix from left up corner to right down. then from right down to left up.
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1, dp[i + 1][j] + 1, dp[i][j + 1] + 1, dp[i] [j - 1] + 1);
Java Code:
public class Solution {
public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
List<List<Integer>> result = new ArrayList<>();
if (null == matrix) {
return result;
}
int m = matrix.size();
int n = matrix.get(0).size();
int maxDistance = m * n;
int[][] distance = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
distance[i][j] = matrix.get(i).get(j) == 0 ? 0 : maxDistance;
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
distance[i][j] = i - 1 >= 0 ? Math.min(distance[i - 1][j] + 1, distance[i][j]) : distance[i][j];
distance[i][j] = j - 1 >= 0 ? Math.min(distance[i][j - 1] + 1, distance[i][j]) : distance[i][j];
}
}
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
distance[i][j] = i + 1 < m ? Math.min(distance[i + 1][j] + 1, distance[i][j]) : distance[i][j];
distance[i][j] = j + 1 < n ? Math.min(distance[i][j + 1] + 1, distance[i][j]) : distance[i][j];
}
}
for (int i = 0; i < m; i++) {
List<Integer> lst = new ArrayList<>();
for (int j = 0; j < n; j++) {
lst.add(distance[i][j]);
}
result.add(lst);
}
return result;
}
}