日常刷题-最小体力消耗

package com.daily.daily20210129;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @Project: dailyCode
 * @Site: http://www.zhao1iang.club/
 * @Copyright: ©CodeLamp
 * @Author: zhaoliang
 * @Create: 2021-01-29 14:35
 * @Desc: 最小体力消耗
 **/
public class minimumEffortPath {
    // 你准备参加一场远足活动。给你一个二维rows x columns的地图heights,
    // 其中heights[row][col]表示格子(row, col)的高度。一开始你在最左上角的格子(0, 0),
    // 且你希望去最右下角的格子(rows-1, columns-1)(注意下标从 0 开始编号)。
    // 你每次可以往 上,下,左,右四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
    //一条路径耗费的 体力值是路径上相邻格子之间 高度差绝对值的 最大值决定的。
    //请你返回从左上角走到右下角的最小体力消耗值。
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        public int minimumEffortPath(int[][] heights) {
            int m = heights.length;
            int n = heights[0].length;
            PriorityQueue<int[]> pq = new PriorityQueue<int[]>((edge1, edge2) -> edge1[2] - edge2[2]);
            pq.offer(new int[]{0, 0, 0});

            int[] dist = new int[m * n];
            Arrays.fill(dist, Integer.MAX_VALUE);
            dist[0] = 0;
            boolean[] seen = new boolean[m * n];

            while (!pq.isEmpty()) {
                int[] edge = pq.poll();
                int x = edge[0], y = edge[1], d = edge[2];
                int id = x * n + y;
                if (seen[id]) {
                    continue;
                }
                if (x == m - 1 && y == n - 1) {
                    break;
                }
                seen[id] = true;
                for (int i = 0; i < 4; ++i) {
                    int nx = x + dirs[i][0];
                    int ny = y + dirs[i][1];
                    if (nx >= 0 && nx < m && ny >= 0 && ny < n && Math.max(d, Math.abs(heights[x][y] - heights[nx][ny])) < dist[nx * n + ny]) {
                        dist[nx * n + ny] = Math.max(d, Math.abs(heights[x][y] - heights[nx][ny]));
                        pq.offer(new int[]{nx, ny, dist[nx * n + ny]});
                    }
                }
            }

            return dist[m * n - 1];
        }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值