- 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
- 46 lines of C++ from the credited upstream file 3342.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 4 int minTimeToReach(vector<vector<int>>& moveTime) {5 return dijkstra(moveTime, {0, 0},6 {moveTime.size() - 1, moveTime[0].size() - 1});7 }8 9 private:10 int dijkstra(const vector<vector<int>>& moveTime, const pair<int, int>& src,11 const pair<int, int>& dst) {12 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};13 const int m = moveTime.size();14 const int n = moveTime[0].size();15 vector<vector<int>> dist(m, vector<int>(n, INT_MAX));16 17 dist[0][0] = 0;18 using T = pair<int, pair<int, int>>; 19 priority_queue<T, vector<T>, greater<>> minHeap;20 minHeap.push({dist[0][0], src});21 22 while (!minHeap.empty()) {23 const auto [d, u] = minHeap.top();24 minHeap.pop();25 if (u == dst)26 return d;27 const auto [i, j] = u;28 if (d > dist[i][j])29 continue;30 for (const auto& [dx, dy] : kDirs) {31 const int x = i + dx;32 const int y = j + dy;33 if (x < 0 || x == m || y < 0 || y == n)34 continue;35 const int newDist = max(moveTime[x][y], d) + ((i + j) % 2 + 1);36 if (newDist < dist[x][y]) {37 dist[x][y] = newDist;38 minHeap.push({newDist, {x, y}});39 }40 }41 }42 43 return -1;44 }45};46