Graph Algorithms (Continued)
Directed graphs, ordering tasks, and the cheapest way to get from A to B.
- detect a directed cycle with DFS
- compute a topological order two ways
- find longest paths in a DAG
- trace Dijkstra and say when it fails
- choose between BFS, Dijkstra, Bellman–Ford and Floyd–Warshall
Directed graphs
In a directed graph, edges have a direction: u → v does not imply v → u. Everything from last week still works (adjacency lists store out-neighbours), but the questions change:
| Undirected | Directed |
|---|---|
| connected | strongly connected: every vertex reaches every other along directed paths |
| cycle: any closed loop | directed cycle: follows edge directions |
| degree | in-degree and out-degree |
A directed graph with no directed cycle is a DAG (directed acyclic graph). DAGs describe dependencies: course prerequisites, tasks in a project, build systems, spreadsheet formulas.
Detecting a directed cycle with DFS
Run DFS and keep three states per vertex: unvisited, in progress (on the current recursion stack), finished. If we ever meet an in-progress vertex, we have walked around a cycle.
In DFS on a directed graph, reaching a vertex that is currently on the recursion stack means…
Topological sort
A topological order lists every vertex so that for every edge u → v, u comes before v. It exists if and only if the graph is a DAG. It tells you a valid order for doing dependent tasks.
Method 1 — Kahn's algorithm (in-degrees)
Vertices with in-degree 0 have no unmet prerequisites. Output one, 'delete' it by decrementing the in-degree of its out-neighbours, and repeat. If we get stuck with vertices left over, a cycle exists.
Method 2 — reverse DFS finish order
Run DFS over all vertices. A vertex finishes only after all vertices reachable from it have finished. So listing vertices in decreasing finish time gives a topological order.
A DAG usually has several topological orders — the two methods may print different ones, and both are correct. Check by verifying every edge goes left to right.
A graph has 5 vertices and the edges A→B, B→C, C→A, C→D, D→E. Does it have a topological order?
Which vertices does Kahn's algorithm start with?
adj = {'shirt': ['tie', 'belt'], 'tie': ['jacket'], 'belt': ['jacket'], 'trousers': ['belt', 'shoes'], 'socks': ['shoes'], 'jacket': [], 'shoes': []}
indeg = {v: 0 for v in adj}
for u in adj:
for v in adj[u]:
indeg[v] += 1
print([v for v in adj if indeg[v] == 0])Kahn's algorithm outputs fewer than n vertices before the queue empties. This indicates…
Longest paths in a DAG
Longest path is NP-hard in general graphs, but in a DAG it is easy: process vertices in topological order, and for each vertex v compute L[v] = 1 + max(L[u] for edges u → v). This gives the critical path of a project: the minimum possible completion time even with unlimited workers.
When we process v, all its predecessors are already done, so L[v] is final. This 'compute in dependency order' pattern is the seed of dynamic programming (Week 9).
Time to compute longest path in a DAG with n vertices and m edges?
Shortest paths: Dijkstra's algorithm
BFS counts edges. With weights (distances, times, costs) the path with fewest edges is not necessarily the cheapest. Dijkstra's algorithm finds the cheapest path from a source s to all vertices, provided no edge weight is negative.
Idea
Maintain a tentative distance d[v] (initially ∞, with d[s] = 0). Repeatedly pick the unfinalised vertex with the smallest tentative distance — its distance is now final — and relax its outgoing edges: if d[u] + w < d[v] then update d[v].
Take the unfinalised vertex u with the smallest d[u]. Any other route to u must leave the finalised set through some other unfinalised vertex whose tentative distance is already ≥ d[u], and adding non-negative weights cannot make it shorter. So d[u] is the true distance.
Your turn. Build a weighted directed graph (use “Set weight” to change costs) and run Dijkstra from any vertex. Switch the algorithm to Topological sort, press “🎲 Random” for an acyclic graph, then add one edge backwards to create a cycle and watch Kahn's algorithm get stuck.
Running time
With the simple scan above: n rounds × O(n) to pick the minimum + O(m) relaxations = O(n²). Using a priority queue (heap) to pick the minimum in O(log n) makes it O((n + m) log n), much better for sparse graphs — we build heaps in Week 6.
Suppose s→a costs 2, s→b costs 3 and b→a costs −5. Dijkstra finalises a with distance 2, but the true shortest route is s→b→a = −2. Greedy finalisation assumes later detours cannot help; negative edges violate that.
What are the shortest distances from vertex 0?
INF = float("inf")
adj = {0: [(1, 4), (2, 1)], 1: [(3, 1)], 2: [(1, 2), (3, 5)], 3: []}
d = {v: INF for v in adj}
d[0] = 0
for _ in range(len(adj)):
for u in adj:
for v, w in adj[u]:
if d[u] + w < d[v]:
d[v] = d[u] + w
print(d)Why does BFS give wrong answers for weighted shortest paths?
In the visualised graph, what is the shortest distance from vertex 0 to vertex 4? (Run Dijkstra or the code above.)
Negative weights: Bellman–Ford and Floyd–Warshall
Bellman–Ford handles negative edges (but not a negative cycle, where distances would decrease forever). A shortest path has at most n − 1 edges, so relaxing every edge n − 1 times is enough. If a further round still improves something, a negative cycle exists. Time: O(n·m).
Floyd–Warshall answers all-pairs shortest paths. Let D[i][j] be the best known distance. For each possible intermediate vertex k in turn, test whether going i → k → j beats going directly. Three nested loops: O(n³).
| Algorithm | Handles | Time |
|---|---|---|
| BFS | unweighted, single source | O(n + m) |
| Dijkstra (heap) | non-negative weights, single source | O((n + m) log n) |
| Bellman–Ford | negative weights, single source | O(n·m) |
| Floyd–Warshall | all pairs, negative weights (no neg. cycle) | O(n³) |
| DAG relaxation | any weights, DAG only, single source | O(n + m) |
You need shortest paths from one source on a graph that may contain negative edge weights (but no negative cycle). Use…
Floyd–Warshall's three nested loops make it…
Chapter challenge — Week 5
Which graphs have a topological order?
What does this program print?
adj = {'a': ['b', 'c'], 'b': ['d'], 'c': ['d'], 'd': []}
seen, fin = set(), []
def go(u):
seen.add(u)
for v in adj[u]:
if v not in seen:
go(v)
fin.append(u)
go('a')
print(fin[::-1])Put Dijkstra's loop in order.
What does this print? (type the exact output)
INF = 10**9
D = [[0, 4, 9], [INF, 0, 3], [INF, INF, 0]]
for k in range(3):
for i in range(3):
for j in range(3):
D[i][j] = min(D[i][j], D[i][k] + D[k][j])
print(D[0][2])Pick all correct statements.
A project has tasks with dependencies, and each takes one day; with unlimited helpers, the minimum days = ?
Kahn's algorithm processes a DAG with 6 vertices. How many vertices are output if the graph is a DAG?
Using a heap, Dijkstra's running time becomes…
Practice on LeetCode
Directed graphs, topological order and weighted shortest paths.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Course Schedule ↗ | Medium | cycle detection / Kahn's algorithm | |
| Course Schedule II ↗ | Medium | output a topological order | |
| Find Eventual Safe States ↗ | Medium | DFS with three states, or reverse Kahn | |
| Network Delay Time ↗ | Medium | Dijkstra | |
| Path with Maximum Probability ↗ | Medium | Dijkstra variant | |
| Path With Minimum Effort ↗ | Medium | Dijkstra on a grid with a different cost | |
| Cheapest Flights Within K Stops ↗ | Medium | Bellman–Ford with a limit on rounds | |
| Find the City With the Smallest Number of Neighbors at a Threshold Distance ↗ | Medium | Floyd–Warshall | |
| Longest Increasing Path in a Matrix ↗ | Hard | longest path in a DAG (memoised DFS) |
Key takeaways
- A DAG has no directed cycle; a topological order exists iff the graph is a DAG, and can be found in O(n + m) with Kahn's algorithm or reverse DFS finish order.
- Longest paths in a DAG are easy: process in topological order (the first taste of dynamic programming).
- Dijkstra: greedy, picks the closest unfinished vertex then relaxes edges; needs non-negative weights; O(n²) simple, O((n + m) log n) with a heap.
- Bellman–Ford handles negative edges in O(nm); Floyd–Warshall gives all-pairs distances in O(n³).