1162. Analysis of Map [map] BFS

1162. Analysis of Map [map] BFS


link

Title Description

Here Insert Picture Description

BFS graph

TreeThe BFS: take root node into the first team, then no brain layer by layer traversal on the line.
Here Insert Picture DescriptionHere Insert Picture Description

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;
        
    }
}
Published 55 original articles · won praise 1 · views 858

Guess you like

Origin blog.csdn.net/weixin_42469108/article/details/105186666
map
Map
Map
map