其他分享
首页 > 其他分享> > 778. Swim in Rising Water

778. Swim in Rising Water

作者:互联网

BFS, using PriorityQueue to poll out the smallest number every time.

The largest number you get will be the result.

class Solution {
    public int swimInWater(int[][] grid) {
        if(grid==null)
            return 0;
        int m = grid.length, n = grid[0].length;
        boolean[][] visited = new boolean[m][n];
        PriorityQueue<int[]> queue = new PriorityQueue<>((a,b)-> grid[a[0]][a[1]]-grid[b[0]][b[1]]);
        queue.offer(new int[]{0,0});
        int[][] dirs={{-1,0},{1,0},{0,-1},{0,1}};
        int res = 0;
        while(!queue.isEmpty()){
            int[] small = queue.poll();
            res = Math.max(res, grid[small[0]][small[1]]);
            if(small[0]==m-1 && small[1]==n-1)
                return res;
            visited[small[0]][small[1]]=true;
            for(int[] dir: dirs){
                int x = small[0]+dir[0];
                int y = small[1]+dir[1];
                if(x>=0&&x<m&&y>=0&&y<n&&!visited[x][y]){
                    queue.offer(new int[]{x,y});
                }
            }
            
        }
        return res;
    }
}

 

标签:Swim,queue,int,res,Water,Rising,new,small,grid
来源: https://www.cnblogs.com/feiflytech/p/16133395.html