题目描述
LeetCode上的1631. 最小体力消耗路径,难度:中等【1948】
你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。
请你返回从左上角走到右下角的最小 体力消耗值 。
示例1:
输入:heights = [[1,2,2],[3,8,2],[5,3,5]]
输出:2
解释:路径 [1,3,5,3,5] 连续格子的差值绝对值最大为 2 。
这条路径比路径 [1,2,2,2,5] 更优,因为另一条路径差值最大值为 3 。
示例2:
输入:heights = [[1,2,3],[3,8,4],[5,3,5]]
输出:1
解释:路径 [1,2,3,4,5] 的相邻格子差值绝对值最大为 1 ,比路径 [1,3,5,3,5] 更优。
示例3:
输入:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
输出:0
解释:上图所示路径不需要消耗任何体力。
提示:
rows == heights.lengthcolumns == heights[i].length1 <= rows, columns <= 1001 <= heights[i][j] <= 106
BFS+动态规划思想
m为地图行的数量,n为地图列的数量
但对于题目中给出的可以向任意方向移动,就需要将其转换为图论问题来解决了,而不是单纯的DP问题。
类似这种路径问题都可以使用BFS/DFS来解决
那么问题来了,向BFS/DFS只负责路径搜索,本题我们在搜索的过程中,记录相邻各自之间的最大插值,当到达目标节点(m-1,n-1)的时候,求出所有搜索路径上的最小体力消耗。
接下来我们拿下面矩阵举例
class Solution {
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int minimumEffortPath(int[][] heights) {
int m = heights.length, n = heights[0].length;
boolean[][] visited = new boolean[m][n];
PriorityQueue<int[]> queue = new PriorityQueue<int[]>((a,b) -> (a[2] - b[2]));
queue.add(new int[] {0, 0, 0});
int ans = Integer.MAX_VALUE;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] poll = queue.poll();
int row = poll[0], col = poll[1], absH = poll[2];
if(visited[row][col]) continue;
visited[row][col] = true;
// 这里在小根堆中满足条件最终位置的元素会有多个
if(row == m - 1 && col == n - 1) {
ans = Math.min(ans, absH);
}
// 遍历四个方向
for(int[] dir : dirs) {
int new_row = row + dir[0], new_col = col + dir[1];
if(new_row >= 0 && new_row < m && new_col >= 0 && new_col < n && !visited[new_row][new_col]) {
queue.add(new int[] {new_row, new_col, Math.max(absH, Math.abs(heights[new_row][new_col] - heights[row][col]))});
}
}
}
}
return ans;
}
}
同样思想的题如下,读者可以自己动手做一下