1162. 地图分析
你现在手里有一份大小为 N x N 的『地图』(网格) grid,上面的每个『区域』(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,你知道距离陆地区域最远的海洋区域是是哪一个吗?请返回该海洋区域到离它最近的陆地区域的距离。
我们这里说的距离是『曼哈顿距离』( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。
如果我们的地图上只有陆地或者海洋,请返回 -1。
示例 1:
输入:[[1,0,1],[0,0,0],[1,0,1]]
输出:2
解释:
海洋区域 (1, 1) 和所有陆地区域之间的距离都达到最大,最大距离为 2。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:BFS广度优先搜索
class Solution {
public int maxDistance(int[][] grid) {
int[] dx={1,-1,0,0};
int[] dy={0,0,1,-1};
Queue<int[]> temp=new ArrayDeque<>();
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
if(grid[i][j]==1)
{
temp.offer(new int[]{i,j});//先将所有陆地存入队列中
}
}
}
boolean hasOcean=false;
int[] cur=null;
while(!temp.isEmpty())//多源广度优先搜索BFS
{
cur=temp.poll();
int x=cur[0];
int y=cur[1];
for(int a=0;a<4;a++)
{
int newx=x+dx[a];
int newy=y+dy[a];
if(newx<0||newy<0||newx>=grid.length||newy>=grid[0].length||grid[newx][newy]!=0)
{
continue;
}
grid[newx][newy]=grid[x][y]+1;//直接在原数组中修改,记录距离
hasOcean=true;
temp.offer(new int[]{newx,newy});//将遍历过的海洋放入队列中,方便进行下一轮BFS
}
}
if(cur==null||!hasOcean)
{
return -1;
}
//返回最后一轮遍历的海洋
return grid[cur[0]][cur[1]]-1;
}
}