8000 refactor 542 · puperfused/Leetcode@140027b · GitHub
[go: up one dir, main page]

Skip to content

Commit 140027b

Browse files
refactor 542
1 parent f89622d commit 140027b

File tree

1 file changed

+27
-22
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+27
-22
lines changed

src/main/java/com/fishercoder/solutions/_542.java

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import java.util.List;
66

77
/**
8+
* 542. 01 Matrix
9+
*
810
* Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
911
1012
The distance between two adjacent cells is 1.
@@ -36,34 +38,37 @@
3638
*/
3739
public class _542 {
3840

39-
public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
40-
int m = matrix.size();
41-
int n = matrix.get(0).size();
42-
Deque<int[]> deque = new LinkedList<>();
43-
for (int i = 0; i < m; i++) {
44-
for (int j = 0; j < n; j++) {
45-
if (matrix.get(i).get(j) == 0) {
46-
deque.offer(new int[]{i, j});
47-
} else {
48-
matrix.get(i).set(j, Integer.MAX_VALUE);
41+
public static class Solution1 {
42+
43+
public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
44+
int m = matrix.size();
45+
int n = matrix.get(0).size();
46+
Deque<int[]> deque = new LinkedList<>();
47+
for (int i = 0; i < m; i++) {
48+
for (int j = 0; j < n; j++) {
49+
if (matrix.get(i).get(j) == 0) {
50+
deque.offer(new int[]{i, j});
51+
} else {
52+
matrix.get(i).set(j, Integer.MAX_VALUE);
53+
}
4954
}
5055
}
51-
}
5256

53-
final int[] dirs = new int[]{0, 1, 0, -1, 0};
54-
while (!deque.isEmpty()) {
55-
int[] currentCell = deque.poll();
56-
for (int i = 0; i < dirs.length - 1; i++) {
57-
int nextRow = currentCell[0] + dirs[i];
58-
int nextCol = currentCell[1] + dirs[i + 1];
59-
if (nextRow < 0 || nextCol < 0 || nextRow >= m || nextCol >= n || matrix.get(nextRow).get(nextCol) <= matrix.get(currentCell[0]).get(currentCell[1]) + 1) {
60-
continue;
57+
final int[] dirs = new int[]{0, 1, 0, -1, 0};
58+
while (!deque.isEmpty()) {
59+
int[] currentCell = deque.poll();
60+
for (int i = 0; i < dirs.length - 1; i++) {
61+
int nextRow = currentCell[0] + dirs[i];
62+
int nextCol = currentCell[1] + dirs[i + 1];
63+
if (nextRow < 0 || nextCol < 0 || nextRow >= m || < 81C7 span class=pl-s1>nextCol >= n || matrix.get(nextRow).get(nextCol) <= matrix.get(currentCell[0]).get(currentCell[1]) + 1) {
64+
continue;
65+
}
66+
deque.offer(new int[]{nextRow, nextCol});
67+
matrix.get(nextRow).set(nextCol, matrix.get(currentCell[0]).get(currentCell[1]) + 1);
6168
}
62-
deque.offer(new int[]{nextRow, nextCol});
63-
matrix.get(nextRow).set(nextCol, matrix.get(currentCell[0]).get(currentCell[1]) + 1);
6469
}
70+
return matrix;
6571
}
66-
return matrix;
6772
}
6873

6974
}

0 commit comments

Comments
 (0)
0