一、题目描述
你现在手里有一份大小为 N x N 的「地图」(网格) grid,上面的每个「区域」(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,请你找出一个海洋区域,这个海洋区域到离它最近的陆地区域的距离是最大的。
我们这里说的距离是「曼哈顿距离」( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。
如果我们的地图上只有陆地或者海洋,请返回 -1。
来源:力扣(LeetCode)
链接:地图分析
二、解题思路
本题可以采用BFS的方式来解答,从陆地出发,然后一层一层地向外遍历海洋,最后到达的海洋就是最远的海洋。代码实现如下所示。解题思路参考sweetiee
import java.util.*;
class Solution {
//定义遍历的方向
private int []dx={-1,0,1,0};
private int []dy={0,1,0,-1};
public int maxDistance(int[][] grid) {
Queue<int[]> queue=new ArrayDeque<int[]>();
int n=grid.length;
int m=grid[0].length;
//把所有的陆地入队列
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
if(grid[i][j]==1)
queue.offer(new int[]{i,j});
}
}
//从陆地出发遍历所有的海洋
int []point=null;
boolean hasOcean=false;
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 >=n || newy <0 || newy>=m || 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;//最后扩展到的海洋就是最远的海洋
}
}