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;
    }
}

 

posted on 2022-04-12 07:30  阳光明媚的菲越  阅读(10)  评论(0编辑  收藏  举报