You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route’s effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
classSolution { int n, m; public: intminimumEffortPath(vector<vector<int>>& heights){ //o(n^2log(n^2)) n = heights.size(), m = heights[0].size(); int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0}; vector<vector<int>> dist(n,vector<int>(m,INT_MAX)); priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq; dist[0][0] = 0; pq.push({0,0,0});
while(!pq.empty()) { auto [effort, y, x] = pq.top(); pq.pop(); if(y == n - 1and x == m - 1) return effort;
for(int i = 0; i < 4; i++) { int ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < n and0 <= nx and nx < m) { int diff = max(effort, abs(heights[y][x] - heights[ny][nx])); if(dist[ny][nx] > diff) { dist[ny][nx] = diff; pq.push({diff, ny, nx}); } } } }