1162. 地图分析【图的BFS】

1162. 地图分析【图的BFS】


链接

题目描述

在这里插入图片描述

图的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;
        
    }
}
发布了55 篇原创文章 · 获赞 1 · 访问量 858

猜你喜欢

转载自blog.csdn.net/weixin_42469108/article/details/105186666