LeetCode 778 题解

https://leetcode.com/problems/swim-in-rising-water/description/

题目大意:N*N的格子,没个格子有一定的高度,每分钟会下1个单位的水,问从左上(0,0)到右下(n-1,n-1)需要最少多少时间。

解题思路:考虑数据范围,高度的范围为 n*n-1, n小于50所以可以枚举一个 完成的时间T,判断该时间能否满足,时间复杂度是n^2能恰好过这题。优化成log(n)的话,可以二分一下这个T。

class Solution {
    private int[] dx={1,0,-1,0};
    private int[] dy={0,1,0,-1};
    public int swimInWater(int[][] grid) {
        int n = grid.length;
        int res =grid[0][0];
        int left = res,right = n*n-1;
        int mid = (left+right) /2 ;

        while(left<=right)
        {
            res= mid;

            int[][] vis = new int[n][n];
            PriorityQueue<Pair> qt = new PriorityQueue<>();
            qt.offer(new Pair(0,0,res));
            vis[0][0] = 1;
            int flag=0;
            while(!qt.isEmpty()) {
                Pair tmp = qt.poll();
                int x = tmp.x;
                int y = tmp.y;
//                System.out.println(x+" "+y+" "+res);
                for (int i = 0; i < 4; i++) {
                    int tx = x + dx[i];
                    int ty = y + dy[i];
                    if (tx < 0 || ty < 0 || tx >= n || ty >= n || vis[tx][ty] == 1
                            || grid[tx][ty] > res) continue;
                    vis[tx][ty] = 1;
                    if (tx == n - 1 && ty == n - 1) { flag=1; break;}
                    qt.offer(new Pair(tx, ty, grid[tx][ty]));
                }
            }
            if(flag==1)
            {
                right = mid-1;
            }
            else
                left = mid+1;
            mid = (left+right) /2;
        }
        return left;
    }
}

class Pair implements Comparable<Pair>{
    public int x,y,val;

    public Pair(int x, int y, int val) {
        this.x = x;
        this.y = y;
        this.val = val;
    }

    @Override
    public int compareTo(Pair o) {
        if(this.val > o.val) return -1;
        if(this.val < o.val) return 1;
        return 0;
    }
}

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/80509940