难度中等127
你准备参加一场远足活动。给你一个二维 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
实际上采用
Dijkstra时间复杂度会更低,这里采用的是BFS和一个DP数组保存到达点的最大消耗体力,通过搜索实时更新。
(不同点在于Dijkstra还需维护一个优先队列,以保证弹出的每个都是最短的)
#define INF (0x3f3f3f3f)
class Solution {
int dir_x[4] = { -1,0,0,1 };
int dir_y[4] = { 0,1,-1,0 };
int val[101][101];
public:
int minimumEffortPath(vector<vector<int>>& heights) {
queue<pair<int, int>>graph;
int res = INF;
int row = heights.size(), col = heights[0].size();
memset(val, INF, sizeof(val));
graph.push(pair<int, int>(0, 0));
val[0][0]=0;
while (!graph.empty()) {
pair<int, int>front = graph.front();
for (int i = 0; i < 4; i++)
{
int xx = front.first + dir_x[i];
int yy = front.second + dir_y[i];
if (xx >= 0 && xx < row && yy >= 0 && yy < col) {
int new_cha = abs(heights[xx][yy] - heights[front.first][front.second]);
if (max(new_cha, val[front.first][front.second]) < val[xx][yy]) {
val[xx][yy] = max(new_cha, val[front.first][front.second]);
//cout << xx << ' ' << yy << ' ' << val[xx][yy] <<endl;
graph.push(pair<int, int>(xx, yy));
}
}
}
graph.pop();
}
return val[row - 1][col - 1];
}
};