- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 47 lines of C++ from the credited upstream file 1631.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 2 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct T {2 int i;3 int j;4 int d; 5};6 7class Solution {8 public:9 int minimumEffortPath(vector<vector<int>>& heights) {10 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};11 const int m = heights.size();12 const int n = heights[0].size();13 auto compare = [](const T& a, const T& b) { return a.d > b.d; };14 priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);15 16 vector<vector<int>> diff(m, vector<int>(n, INT_MAX));17 vector<vector<bool>> seen(m, vector<bool>(n));18 19 minHeap.emplace(0, 0, 0);20 diff[0][0] = 0;21 22 while (!minHeap.empty()) {23 const auto [i, j, d] = minHeap.top();24 minHeap.pop();25 if (i == m - 1 && j == n - 1)26 return d;27 seen[i][j] = true;28 for (const auto& [dx, dy] : kDirs) {29 const int x = i + dx;30 const int y = j + dy;31 if (x < 0 || x == m || y < 0 || y == n)32 continue;33 if (seen[x][y])34 continue;35 const int newDiff = abs(heights[i][j] - heights[x][y]);36 const int maxDiff = max(diff[i][j], newDiff);37 if (diff[x][y] > maxDiff) {38 diff[x][y] = maxDiff;39 minHeap.emplace(x, y, maxDiff);40 }41 }42 }43 44 throw;45 }46};47