01
Dijkstra (Shortest Paths (Weighted) Sub-pattern)
Cheapest route from one source when every edge cost is ≥ 0, including scores built with max or multiplication.
Signals in the problem statement
- ›
"minimum time for all nodes to receive the signal"
- ›
"path with maximum probability"
- ›
"minimum effort" = the largest step along the path
What makes it different
Dijkstra (template) and Network Delay Time are plain sums; Network Delay answers the largest final distance, or -1 if a node is unreachable. Path with Maximum Probability multiplies and pops the largest first. Path With Minimum Effort runs on grid cells, and a path's cost is max(cost so far, |height difference|).
Questions
ordered from “learn the idea” to “recognise it without help”- 1Dijkstra's Algorithm (template)WalkthroughMediumBasic Anchor·GeeksforGeeks
- 2Network Delay TimeWalkthroughMediumBasic Reinforcement·LeetCode #743
- 3Path with Maximum ProbabilityWalkthroughMediumSlight Variation·LeetCode #1514
- 4Path With Minimum EffortWalkthroughMediumMedium·LeetCode #1631
Template
dijkstra-template.cpp
// Dijkstra: always settle the closest unsettled node; its distance can't improve later.
// Works when every edge weight is >= 0.
vector<long long> dijkstra(int n, const vector<vector<pair<int, int>>>& adj, int src) { // adj[u] = {v, w}
const long long INF = LLONG_MAX;
vector<long long> dist(n, INF);
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq; // {dist, node}, min first
dist[src] = 0;
pq.push({0, src});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d > dist[u]) continue; // stale entry: u was settled with a smaller d
for (auto [v, w] : adj[u])
if (d + w < dist[v]) { // relax: a shorter way to v through u
dist[v] = d + w;
pq.push({dist[v], v});
}
}
return dist; // INF = unreachable
}Remember this · Shortest Paths (Weighted)
Trigger
Weighted edges, "minimum cost / time / effort", at most K stops, negative weights, all-pairs distances.
Think
Are edge weights non-negative (Dijkstra), limited by stops (Bellman-Ford), or do I need every pair (Floyd)?
Key question
What is a node's "distance", and when is it final?