- 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
- 39 lines of C++ from the credited upstream file 2577.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.
1class Solution {2 public:3 int minimumTime(vector<vector<int>>& grid) {4 if (grid[0][1] > 1 && grid[1][0] > 1)5 return -1;6 7 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};8 const int m = grid.size();9 const int n = grid[0].size();10 using T = tuple<int, int, int>; 11 priority_queue<T, vector<T>, greater<>> minHeap;12 vector<vector<bool>> seen(m, vector<bool>(n));13 14 minHeap.emplace(0, 0, 0);15 seen[0][0] = true;16 17 while (!minHeap.empty()) {18 const auto [time, i, j] = minHeap.top();19 minHeap.pop();20 if (i == m - 1 && j == n - 1)21 return time;22 for (const auto& [dx, dy] : kDirs) {23 const int x = i + dx;24 const int y = j + dy;25 if (x < 0 || x == m || y < 0 || y == n)26 continue;27 if (seen[x][y])28 continue;29 const int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0;30 const int nextTime = max(time + 1, grid[x][y] + extraWait);31 minHeap.emplace(nextTime, x, y);32 seen[x][y] = true;33 }34 }35 36 throw;37 }38};39