1631. Minimal physical exertion path
Medium difficulty 127
You are going to participate in a hike. Give you a two-dimensional rows x columns
map heights
, which heights[row][col]
represents (row, col)
the height of the grid . At first you are in the top left corner of the grid (0, 0)
, and you want to go to the bottom right corner of the grid (rows-1, columns-1)
(note that the subscript number starts from 0 ). Every time you can go on , down , left , and right one of four directions, you want to find consume physical smallest path.
The physical energy consumed by a path is determined by the maximum absolute value of the height difference between adjacent grids on the path .
Please return the minimum physical exertion value for walking from the upper left corner to the lower right corner .
Example 1:
Input: heights = [[1,2,2],[3,8,2],[5,3,5]] Output: 2 Explanation: Path [1,3,5,3,5] the difference of consecutive grids The maximum absolute value of the value is 2. This path is better than path [1,2,2,2,5] because the maximum difference of the other path is 3.
Example 2:
Input: heights = [[1,2,3],[3,8,4],[5,3,5]] Output: 1 Explanation: The adjacent grid of path [1,2,3,4,5] The maximum absolute value of the difference is 1, which is better than the path [1,3,5,3,5].
Example 3:
Input: 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]] Output: 0 Explanation: The path shown in the figure above does not require any physical effort.
prompt:
rows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 106
实际上采用
Dijkstra's time complexity will be lower. Here, BFS and a DP array are used to save the maximum energy consumption of the arrival point, which is updated in real time through search.
(The difference is that Dijkstra also needs to maintain a priority queue to ensure that each pop-up is the shortest)
#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];
}
};