当前位置: 代码迷 >> 综合 >> Leetcode 1631:最小体力消耗路径
  详细解决方案

Leetcode 1631:最小体力消耗路径

热度:71   发布时间:2024-03-08 09:51:07.0

题目描述

你准备参加一场远足活动。给你一个二维 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.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 106

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-with-minimum-effort
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

解题思路

class Solution {
public:int minimumEffortPath(vector<vector<int>>& heights) {int rows = heights.size();int cols = heights[0].size();vector<vector<int>> dp(rows, vector<int>(cols, INT_MAX));vector<int> dx = {-1, 0, 1, 0};vector<int> dy = {0, 1, 0, -1};queue<pair<int, int>> que;que.push(make_pair(0, 0));dp[0][0] = 0;while(!que.empty()){int n = que.size();for(int i = 0; i < n; i++){auto tmp = que.front();que.pop();int x = tmp.first;int y = tmp.second;for(int j = 0; j < 4; j++){int tx = x + dx[j];int ty = y + dy[j];if(tx >= 0 && tx < rows && ty >= 0 && ty < cols){int tmp = max(dp[x][y], abs(heights[tx][ty] - heights[x][y]));if(tmp >= dp[tx][ty]) continue;dp[tx][ty] = tmp;que.push(make_pair(tx, ty));}}}}return dp[rows-1][cols-1];}
};