链接
题目描述
图的BFS
Tree
的 BFS : 要把 root 节点先入队,然后再一层一层的无脑遍历就行了。
class Solution {
public int maxDistance(int[][] grid) {
//图的BFS
//首先把所有陆地都入队列,然后取出一个,把周围的入队列
int[] dx = new int[]{0,0,1,-1};
int[] dy = new int[]{1,-1,0,0};
boolean hasOcean = false;
//所有陆地入队列
Queue<int[]> queue = new LinkedList();
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});
}
}
}
int[] point = null;
while(!queue.isEmpty()){
point = queue.poll();
int x = point[0];
int 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;
}
hasOcean = true;
grid[newX][newY] = grid[x][y] + 1;
queue.offer(new int[]{newX,newY});
}
}
//如果没有海洋或者没有陆地
if(!hasOcean || point == null){
return -1;
}
return grid[point[0]][point[1]] -1;
}
}