Skip to content

Commit ae5705b

Browse files
authored
Create week5 542. 01 Matrix.
1 parent 7e67de4 commit ae5705b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

week5 542. 01 Matrix.

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
public class Solution {
2+
public int[][] updateMatrix(int[][] matrix) {
3+
int m = matrix.length;
4+
int n = matrix[0].length;
5+
6+
Queue<int[]> queue = new LinkedList<>();
7+
for (int i = 0; i < m; i++) {
8+
for (int j = 0; j < n; j++) {
9+
if (matrix[i][j] == 0) {
10+
queue.offer(new int[] {i, j});
11+
}
12+
else {
13+
matrix[i][j] = Integer.MAX_VALUE;
14+
}
15+
}
16+
}
17+
18+
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
19+
20+
while (!queue.isEmpty()) {
21+
int[] cell = queue.poll();
22+
for (int[] d : dirs) {
23+
int r = cell[0] + d[0];
24+
int c = cell[1] + d[1];
25+
if (r < 0 || r >= m || c < 0 || c >= n ||
26+
matrix[r][c] <= matrix[cell[0]][cell[1]] + 1) continue;
27+
queue.add(new int[] {r, c});
28+
matrix[r][c] = matrix[cell[0]][cell[1]] + 1;
29+
}
30+
}
31+
32+
return matrix;
33+
}
34+
}

0 commit comments

Comments
 (0)