Skip to content

Commit 6368ca6

Browse files
authored
Create Solution.java
1 parent ab06b7f commit 6368ca6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

solution/0542.01 Matrix/Solution.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public int[][] updateMatrix(int[][] matrix) {
3+
int m = matrix.length, n = matrix[0].length;
4+
int[][] res = new int[m][n];
5+
for (int[] arr : res) {
6+
Arrays.fill(arr, -1);
7+
}
8+
class Position {
9+
int x, y;
10+
11+
public Position(int x, int y) {
12+
this.x = x;
13+
this.y = y;
14+
}
15+
}
16+
Queue<Position> queue = new ArrayDeque<>();
17+
for (int i = 0; i < m; ++i) {
18+
for (int j = 0; j < n; ++j) {
19+
if (matrix[i][j] == 0) {
20+
res[i][j] = 0;
21+
queue.offer(new Position(i, j));
22+
}
23+
}
24+
}
25+
int[] dirs = new int[]{-1, 0, 1, 0, -1};
26+
while (!queue.isEmpty()) {
27+
Position pos = queue.poll();
28+
for (int i = 0; i < 4; ++i) {
29+
int x = pos.x + dirs[i], y = pos.y + dirs[i + 1];
30+
if (x >= 0 && x < m && y >= 0 && y < n && res[x][y] == -1) {
31+
res[x][y] = res[pos.x][pos.y] + 1;
32+
queue.offer(new Position(x, y));
33+
}
34+
}
35+
}
36+
return res;
37+
}
38+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy