【1631 最小体力消耗路径】
题目描述
你准备参加一场远足活动。给你一个二维 rows x columns
的地图 heights
,其中 heights[row][col]
表示格子 (row, col)
的高度。一开始你在最左上角的格子 (0, 0)
,且你希望去最右下角的格子 (rows-1, columns-1)
(注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。
请你返回从左上角走到右下角的最小 体力消耗值 。
解法1:Dijkstra 变体
图 + 优先队列
class Solution {
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[]>(new Comparator<int[]>() {
public int compare(int[] edge1, int[] edge2) {
return edge1[2] - edge2[2];
}
});
// x,y 坐标 d:节点权值
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) {
if (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];
}
}
解法2:并查集
待整理…