题目描述:
你现在手里有一份大小为 N x N 的「地图」(网格) grid,上面的每个「区域」(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,请你找出一个海洋区域,这个海洋区域到离它最近的陆地区域的距离是最大的。
我们这里说的距离是「曼哈顿距离」( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。
如果我们的地图上只有陆地或者海洋,请返回 -1。
解法一: BFS
- 建立一个队列,将所有的陆地入队,然后开始出队,将周围的海洋变成陆地入队,入队后直接在原位置上+1作为标记,防止重复入队,最终出队的位置就是最远的海洋的位置。
- 最后的位置的值-1 就是最远的距离。
时间复杂度: O(N); 辅助空间复杂度: O(N)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public int maxDistance(int[][] grid) { int[] dx = {0, 0, 1, -1}; int[] dy = {1, -1, 0, 0};
Queue<int[]> queue = new ArrayDeque<>(); int m = grid.length, n = grid[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { queue.offer(new int[] {i, j}); } } }
boolean hasOcean = false; int[] point = null; while (!queue.isEmpty()) { point = queue.poll(); int x = point[0], y = point[1]; for (int i = 0; i < 4; i++) { int newX = x + dx[i]; int newY = y + dy[i]; if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] != 0) { continue; } grid[newX][newY] = grid[x][y] + 1; hasOcean = true; queue.offer(new int[] {newX, newY}); } }
if (point == null || !hasOcean) { return -1; }
return grid[point[0]][point[1]] - 1;
} }
|