地图分析
bfs(填满整个表格)
代码:
class Solution {
public int maxDistance(int[][] grid) {
int[] dx={1,0,-1,0};
int[] dy={0,1,0,-1};
Queue<int[]> queue=new ArrayDeque<>();
int len=grid.length;
for(int i=0;i<len;i++)
for(int j=0;j<len;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>=len || newY<0 ||newY>=len || grid[newX][newY]!=0)continue;
queue.offer(new int[]{newX,newY});
grid[newX][newY]=grid[x][y]+1;
hasOcean=true;
}
}
if(point == null ||!hasOcean)return -1;
return grid[point[0]][point[1]]-1;
}
}
腐烂的橘子
代码:
class Solution {
public static int orangesRotting(int[][] grid) {
int[] dx={1,0,-1,0};
int[] dy={0,1,0,-1};
int m=grid.length;
int n=grid[0].length;
if(n==1 && m==1){
if(grid[0][0]==0||grid[0][0]==2)return 0;
else if(grid[0][0]==1)return -1;
}
Queue<int[]> queue=new ArrayDeque<>();
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
if(grid[i][j]==2){
queue.offer(new int[]{i,j});
}
}
//boolean has=false;
int cnt=0;
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|| grid[newX][newY]>=2)continue;
queue.offer(new int []{newX,newY});
grid[newX][newY]=grid[x][y]+1;
}
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
if(grid[i][j]==1){
return -1;
}
}
return grid[point[0]][point[1]]-2;
}
}
思路:
BFS广度优先遍历,保存一个或多个节点,对数组进行遍历。