Graph Algorithms
Lesson 17 of 20Follow Dijkstra settle the cheapest routes on a priced map — then watch Prim wire the same map for less.
Weighted world
Put a number on every edge and the questions change: not "can we get there" but "how cheaply". Dijkstra, MST and topo sort answer them.
Weights change it all
A weight is a price or a distance. The cheapest route to D can skip the direct cable and detour through two cheap ones.
Dijkstra’s greedy bet
Settle the cheapest unsettled node each round — its distance is final. Non-negative weights make the bet safe.
Relaxation
If dist[u] + w < dist[v], the route through u is cheaper — lower dist[v]. One comparison drives the whole algorithm.
Minimum spanning tree
n − 1 edges that connect every node for the least total weight. Prim grows it from a seed; Kruskal sorts edges and unions.
Order from dependencies
Directed acyclic graphs give build orders: Kahn’s algorithm keeps outputting tasks with in-degree 0. Leftovers = cycle.
Dijkstra settles
Green = settled, distance locked. Amber = frontier with a tentative price. Watch 12 beat 14.
A priced map — the number on each cable is its cost. Dijkstra starts at A: dist 0; everyone else sits at ∞.
The Dijkstra loop
Five stages, V rounds — the whole algorithm in five boxes.
Walkthrough
Array-scan Dijkstra over the priced map — then Kahn’s build-order sort.
1#include <iostream>2#include <vector>3using namespace std;4int main() {5vector<vector<pair<int,int>>> adj = {6{{2,2},{1,8}}, {{0,8},{2,9},{3,6}}, {{0,2},{4,3},{1,9}}, {{4,7},{1,6}}, {{2,3},{3,7}}7};8int n = 5, src = 0, INF = 1000000;9vector<int> dist(n, INF);10vector<bool> done(n, false);11dist[src] = 0;12for (int r = 0; r < n; r++) {13int u = -1;14for (int i = 0; i < n; i++)15if (!done[i] && (u == -1 || dist[i] < dist[u])) u = i;16done[u] = true;17for (auto [v, w] : adj[u])18if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;19}20for (int i = 0; i < n; i++) cout << i << "=" << dist[i] << " ";21return 0;22}
A weighted adjacency list — every entry is {neighbor, weight}. Node 0 reaches 2 for price 2 and 1 for price 8.
Prim wires it cheap
The tree grows one cheapest crossing cable at a time until all five nodes are wired.
Same priced map, new mission: connect every node for the least total cost. Prim grows one tree from A.
Predict the output
The relax test in isolation — one comparison decides everything.
1#include <iostream>2using namespace std;34int main() {5int dist[5] = {0, 8, 2, 14, 5};6int u = 4, v = 3, w = 7;7if (dist[u] + w < dist[v]) {8dist[v] = dist[u] + w;9cout << "improved to " << dist[v] << endl;10} else {11cout << "kept " << dist[v] << endl;12}13cout << "dist[3] = " << dist[3] << endl;14return 0;15}
Hint: The relax rule: dist[u] + w versus dist[v]. Here 5 + 7 = 12 undercuts 14, so dist[3] is lowered.
Concept check
Click a term, then click its meaning to lock the pair.
Key takeaways
Dijkstra settles the cheapest unsettled node each round — exact for non-negative weights.
The relax rule: dist[u] + w < dist[v] means the route through u wins — lower dist[v].
Array-scan Dijkstra is O(V²); a priority queue brings it down to O((V + E) log V).
A spanning tree has exactly n − 1 edges; the MST is the cheapest such set.
Prim grows from a seed node; Kruskal sorts edges and unions components.
Shortest routes and cheapest wiring are different questions — our map answers 12 vs a 6-cable.
Kahn’s topo sort outputs zero-in-degree tasks; anything left over proves a cycle.