Topological Sort (Kahn) visualization
Order a DAG so every edge points forward, by repeatedly removing zero in-degree vertices.
A vertex with in-degree 0 has no unmet prerequisites, so it can go next. Removing it lowers its successors' in-degrees, possibly freeing them.
Edge case: if a cycle exists, its vertices never reach in-degree 0 — the output is shorter than V, which is exactly how Kahn's algorithm detects cycles.
Complexity
Time: best O(V + E), average O(V + E), worst O(V + E). Space: O(V). Difficulty: Intermediate.
Pseudocode
procedure topoSort(G):
indeg[v] ← number of incoming edges
queue ← every v with indeg[v] = 0
while queue not empty:
u ← dequeue; order.append(u)
for each edge u → v:
indeg[v] ← indeg[v] − 1
if indeg[v] = 0: enqueue v
if |order| < |V|: the graph has a cycleMore graphs algorithms
- Breadth-First Search — Explore level by level with a queue — gives shortest paths in unweighted graphs.
- Depth-First Search — Go as deep as possible along each branch before backtracking.
- Dijkstra's Shortest Path — Greedily settle the closest unsettled vertex using a priority queue.
- Bellman–Ford — Relax every edge V−1 times; handles negative weights and detects negative cycles.
- Prim's MST — Grow one tree by always adding the cheapest edge leaving it.
- Kruskal's MST — Sort edges by weight and add each one unless it would create a cycle (union–find).
- Floyd–Warshall — All-pairs shortest paths by allowing one more intermediate vertex k at a time.
- A* Pathfinding — Best-first search on a grid using cost-so-far g plus a heuristic h towards the goal.