BFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { private static final int[][] DIRECTIONS = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int[][] updateMatrix(int[][] mat) { int m = mat.length, n = mat[0].length;
Queue<int[]> queue = new LinkedList<>();
int[][] res = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (mat[i][j] == 0) { queue.offer(new int[]{i, j}); } else { res[i][j] = -1; } } }
while (!queue.isEmpty()) { int[] point = queue.poll(); for (int[] direction : DIRECTIONS) { int nextI = point[0] + direction[0]; int nextJ = point[1] + direction[1]; if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && res[nextI][nextJ] == -1) { res[nextI][nextJ] = res[point[0]][point[1]] + 1; queue.offer(new int[]{nextI, nextJ}); } } }
return res; } }
|
以上是多源 BFS。
DP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { private static final int[][] DIRECTIONS = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int[][] updateMatrix(int[][] mat) { int m = mat.length, n = mat[0].length;
int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (mat[i][j] == 1) { dp[i][j] = Integer.MAX_VALUE / 2; } } }
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i - 1 >= 0) { dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1); } if (j - 1 >= 0) { dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + 1); } } }
for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (i + 1 < m) { dp[i][j] = Math.min(dp[i][j], dp[i + 1][j] + 1); } if (j + 1 < n) { dp[i][j] = Math.min(dp[i][j], dp[i][j + 1] + 1); } } }
return dp; } }
|
References
542. 01 Matrix
剑指 Offer II 107. 矩阵中的距离