Graph Algorithms

Lesson 17 of 20

Follow Dijkstra settle the cheapest routes on a priced map — then watch Prim wire the same map for less.

The big picture

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.