forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_542.java
95 lines (89 loc) · 3.58 KB
/
_542.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.fishercoder.solutions;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class _542 {
public static class Solution1 {
public int[][] updateMatrix(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[][] ans = new int[m][n];
Deque<int[]> deque = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 0) {
deque.offer(new int[]{i, j});
} else {
ans[i][j] = m * n;
}
}
}
int[] directions = new int[]{0, 1, 0, -1, 0};
while (!deque.isEmpty()) {
int[] curr = deque.poll();
for (int i = 0; i < directions.length - 1; i++) {
int nextX = directions[i] + curr[0];
int nextY = directions[i + 1] + curr[1];
if (nextX >= 0 && nextX < m && nextY >= 0 && nextY < n && ans[nextX][nextY] > ans[curr[0]][curr[1]] + 1) {
deque.offer(new int[]{nextX, nextY});
ans[nextX][nextY] = ans[curr[0]][curr[1]] + 1;
}
}
}
return ans;
}
}
public static class Solution2 {
/**
* A silly, but working solution. Apparently, the above BFS approach is a smarter version of this one.
*/
public int[][] updateMatrix(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[][] ans = new int[m][n];
Queue<int[]> queue = new LinkedList<>();
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 {
ans[i][j] = m * n;
}
}
}
while (!queue.isEmpty()) {
int[] curr = queue.poll();
for (int i = curr[0] + 1, j = curr[1]; i < m && mat[i][j] != 0; i++) {
ans[i][j] = Math.min(ans[i][j], i - curr[0]);
}
for (int i = curr[0] - 1, j = curr[1]; i >= 0 && mat[i][j] != 0; i--) {
ans[i][j] = Math.min(ans[i][j], curr[0] - i);
}
for (int j = curr[1] + 1, i = curr[0]; j < n && mat[i][j] != 0; j++) {
ans[i][j] = Math.min(ans[i][j], j - curr[1]);
}
for (int j = curr[1] - 1, i = curr[0]; j >= 0 && mat[i][j] != 0; j--) {
ans[i][j] = Math.min(ans[i][j], curr[1] - j);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i + 1 < m && ans[i + 1][j] >= 1) {
ans[i][j] = Math.min(ans[i][j], ans[i + 1][j] + 1);
}
if (i - 1 >= 0 && ans[i - 1][j] >= 1) {
ans[i][j] = Math.min(ans[i][j], ans[i - 1][j] + 1);
}
if (j + 1 < n && ans[i][j + 1] >= 1) {
ans[i][j] = Math.min(ans[i][j], ans[i][j + 1] + 1);
}
if (j - 1 >= 0 && ans[i][j - 1] >= 1) {
ans[i][j] = Math.min(ans[i][j], ans[i][j - 1] + 1);
}
}
}
return ans;
}
}
}