|
1 | 1 | class Solution {
|
2 |
| - public int maxDistance(int[][] grid) { |
3 |
| - if (grid.length == 0 || grid[0].length == 0) { |
4 |
| - return -1; |
| 2 | + private final int[][] DIRS = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}}; |
| 3 | + |
| 4 | + public int maxDistance(int[][] grid) { |
| 5 | + Queue<int[]> queue = new LinkedList<>(); |
| 6 | + int numRows = grid.length; |
| 7 | + int numCols = grid[0].length; |
| 8 | + for (int i = 0; i < numRows; i++) { |
| 9 | + for (int j = 0; j < numCols; j++) { |
| 10 | + if (grid[i][j] == 1) { |
| 11 | + queue.add(new int[]{i, j}); |
5 | 12 | }
|
6 |
| - int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
7 |
| - boolean[][] visited = new boolean[grid.length][grid[0].length]; |
8 |
| - Queue<int[]> queue = new LinkedList<>(); |
9 |
| - for (int i = 0; i < grid.length; i++) { |
10 |
| - for (int j = 0; j < grid[0].length; j++) { |
11 |
| - if (grid[i][j] == 1) { |
12 |
| - queue.add(new int[]{i, j}); |
13 |
| - visited[i][j] = true; |
14 |
| - } |
15 |
| - } |
16 |
| - } |
17 |
| - int maxDist = -1; |
18 |
| - while (!queue.isEmpty()) { |
19 |
| - int size = queue.size(); |
20 |
| - while (size-- > 0) { |
21 |
| - int[] curr = queue.remove(); |
22 |
| - for (int[] dir : dirs) { |
23 |
| - int x = curr[0] + dir[0]; |
24 |
| - int y = curr[1] + dir[1]; |
25 |
| - if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && !visited[x][y] && grid[x][y] == 0) { |
26 |
| - visited[x][y] = true; |
27 |
| - queue.add(new int[]{x, y}); |
28 |
| - } |
29 |
| - } |
30 |
| - } |
31 |
| - maxDist++; |
| 13 | + } |
| 14 | + } |
| 15 | + if (queue.isEmpty() || queue.size() == numRows * numCols) { |
| 16 | + return -1; |
| 17 | + } |
| 18 | + int distance = 0; |
| 19 | + while (!queue.isEmpty()) { |
| 20 | + int size = queue.size(); |
| 21 | + while (size-- > 0) { |
| 22 | + int[] removed = queue.remove(); |
| 23 | + for (int[] dir : DIRS) { |
| 24 | + int x = removed[0] + dir[0]; |
| 25 | + int y = removed[1] + dir[1]; |
| 26 | + if (x < 0 || y < 0 || x >= numRows || y >= numCols || grid[x][y] == 1) { |
| 27 | + continue; |
| 28 | + } |
| 29 | + grid[x][y] = 1; |
| 30 | + queue.add(new int[]{x, y}); |
32 | 31 | }
|
33 |
| - |
34 |
| - return maxDist == 0 ? -1 : maxDist; |
| 32 | + } |
| 33 | + distance++; |
35 | 34 | }
|
| 35 | + return distance - 1; |
| 36 | + } |
36 | 37 | }
|
0 commit comments