zoukankan      html  css  js  c++  java
  • 778. 水位上升的泳池中游泳

    在一个 N x N 的坐标方格 grid 中,每一个方格的值 grid[i][j] 表示在位置 (i,j) 的平台高度。

    现在开始下雨了。当时间为 t 时,此时雨水导致水池中任意位置的水位为 t 。你可以从一个平台游向四周相邻的任意一个平台,但是前提是此时水位必须同时淹没这两个平台。假定你可以瞬间移动无限距离,也就是默认在方格内部游动是不耗时的。当然,在你游泳的时候你必须待在坐标方格里面。

    你从坐标方格的左上平台 (0,0) 出发。最少耗时多久你才能到达坐标方格的右下平台 (N-1, N-1)

    示例 1:

    输入: [[0,2],[1,3]]
    输出: 3
    解释:
    时间为0时,你位于坐标方格的位置为 (0, 0)。
    此时你不能游向任意方向,因为四个相邻方向平台的高度都大于当前时间为 0 时的水位。
    
    等时间到达 3 时,你才可以游向平台 (1, 1). 因为此时的水位是 3,坐标方格中的平台没有比水位 3 更高的,所以你可以游向坐标方格中的任意位置
    

    示例2:

    输入: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
    输出: 16
    解释:
     0  1  2  3  4
    24 23 22 21  5
    12 13 14 15 16
    11 17 18 19 20
    10  9  8  7  6
    
    最终的路线用加粗进行了标记。
    我们必须等到时间为 16,此时才能保证平台 (0, 0) 和 (4, 4) 是连通的
    

    提示:

    1. 2 <= N <= 50.
    2. grid[i][j] 是 [0, ..., N*N - 1] 的排列。
    class Solution {
        public int swimInWater(int[][] grid) {
            //initialization
            int[][] moves=new int[][]{{0,-1},{-1,0},{1,0},{0,1}};
            int n=grid.length,m=grid[0].length;
            Queue<int[]> queue=new PriorityQueue<>(Comparator.comparingInt(x->x[2]));//use Comparator for grid[i][j]
            boolean[][] vis=new boolean[n][m];
    
            //dfs begins
            queue.offer(new int[]{0,0,grid[0][0]});
            while(!queue.isEmpty()){
                int[] t=queue.poll();
                if(t[0]==n-1&&t[1]==m-1)return t[2];//meets the bottom right square!return t[2]
                for(int[] move:moves){
                    int x=t[0]+move[0],y=t[1]+move[1];//moving~
                    if(x<0||x>=n||y<0||y>=m)continue;//not valid!!continue!
                    if(vis[x][y])continue;//already visited!!continue!
                    vis[x][y]=true;//not visited,set it true
                    queue.offer(new int[]{x,y,Math.max(t[2],grid[x][y])});//offer the new one with max elevation to queue
                }
            }
    
            return -1;
        }
    }
  • 相关阅读:
    【一句日历】2020年3月
    写给我们项目总监的一些话
    基于ajax 的 几个例子 session ,ajax 实现登录,验证码 ,实现ajax表单展示
    day 51 随机验证码, 验证登陆 ,以及 装饰器在函数中的应用
    day 51 cooike 与 session
    day 50 AJAX 初入门
    day 38 jq 入门 学习(一)
    转的大佬的 学习方法
    day 49 数据分析, 数据聚合 F 查询 Q 查询
    day 48 ORM 进阶 多表连接 创建 以及 html模板继承
  • 原文地址:https://www.cnblogs.com/xxxsans/p/14348614.html
Copyright © 2011-2022 走看看