Visualize

Pattern visualizer

Kahn's Algorithm BFS Topological Sort

A topological order lists the vertices so every arrow points forward. Kahn's idea: a vertex with no incoming arrows can safely go first, and once it is out, the arrows leaving it no longer matter — so the vertices it pointed at may become safe too. Keep one number per vertex, its remaining incoming count, and a queue of vertices whose count has hit 0. Popping from the front and pushing newly freed vertices at the back is what makes it breadth-first. The picture draws one directed arrow per edge and shows the remaining count as a badge. Animated on: numVertices = 4, edges = [[3,0],[3,1],[2,1],[1,0]] (a->b means a comes before b) — return a topological ordering using Kahn's BFS algorithm..

Kahn's algorithm: output vertices as their incoming edges clear

time O(V + E)space O(V + E)step 1 / 11

A directed acyclic graph

line 1

4 vertices, 4 directed edges, and an arrow a to b means a must come before b. The task asks for an ORDER, so the plan is to output vertices one at a time and only ever output a vertex once everything pointing at it is already out.

Pseudocode
1FUNCTION topoSort(n, edges):
2 FOR v FROM 0 TO n - 1
3 indeg[v] <- 0
4 FOR EACH (a, b) IN edges
5 APPEND b TO next[a]
6 indeg[b] <- indeg[b] + 1
7 queue <- EVERY v WHERE indeg[v] = 0
8 order <- EMPTY LIST
9 WHILE queue NOT EMPTY
10 v <- REMOVE FIRST FROM queue
11 APPEND v TO order
12 FOR EACH w IN next[v]
13 indeg[w] <- indeg[w] - 1
14 IF indeg[w] = 0
15 APPEND w TO queue
16 RETURN order

← / → step · space play · Home restart

Where to practice Graph