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