- 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
- 41 lines of C++ from the credited upstream file 743.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 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 networkDelayTime(vector<vector<int>>& times, int n, int k) {4 vector<vector<pair<int, int>>> graph(n);5 6 for (const vector<int>& time : times) {7 const int u = time[0] - 1;8 const int v = time[1] - 1;9 const int w = time[2];10 graph[u].emplace_back(v, w);11 }12 13 return dijkstra(graph, k - 1);14 }15 16 private:17 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src) {18 vector<int> dist(graph.size(), INT_MAX);19 20 dist[src] = 0;21 using P = pair<int, int>; 22 priority_queue<P, vector<P>, greater<>> minHeap;23 minHeap.emplace(dist[src], src);24 25 while (!minHeap.empty()) {26 const auto [d, u] = minHeap.top();27 minHeap.pop();28 if (d > dist[u])29 continue;30 for (const auto& [v, w] : graph[u])31 if (d + w < dist[v]) {32 dist[v] = d + w;33 minHeap.emplace(dist[v], v);34 }35 }36 37 const int maxDist = ranges::max(dist);38 return maxDist == INT_MAX ? -1 : maxDist;39 }40};41