|
5 | 5 | import java.util.List;
|
6 | 6 |
|
7 | 7 | /**
|
| 8 | + * 542. 01 Matrix |
| 9 | + * |
8 | 10 | * Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
|
9 | 11 |
|
10 | 12 | The distance between two adjacent cells is 1.
|
|
36 | 38 | */
|
37 | 39 | public class _542 {
|
38 | 40 |
|
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 | + } |
49 | 54 | }
|
50 | 55 | }
|
51 |
| - } |
52 | 56 |
|
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); |
61 | 68 | }
|
62 |
| - deque.offer(new int[]{nextRow, nextCol}); |
63 |
| - matrix.get(nextRow).set(nextCol, matrix.get(currentCell[0]).get(currentCell[1]) + 1); |
64 | 69 | }
|
| 70 | + return matrix; |
65 | 71 | }
|
66 |
| - return matrix; |
67 | 72 | }
|
68 | 73 |
|
69 | 74 | }
|
0 commit comments