v9.1.1
Menu

Chapter 8: Advanced Graphs

Week 8

Explore advanced graph algorithms including topological sort, shortest paths in weighted graphs, and minimum spanning trees. Master Kahn's algorithm, Dijkstra's algorithm, Kruskal's and Prim's algorithms, and solve classic problems like course scheduling and alien dictionary.

Topics
5
Demos
5
Min read
21

Chapter Overview

Building on the graph fundamentals from the previous chapter, we now tackle algorithms that exploit special graph structures --- directed acyclic graphs (DAGs), weighted edges, and global optimization over all edges.

These algorithms power real-world systems: build systems use topological sort to determine compilation order, GPS navigation uses Dijkstra's algorithm to find the fastest route, and network design uses minimum spanning trees to minimize wiring costs.

This chapter covers five key areas:

  • Topological Sort: Ordering vertices in a DAG so every edge points forward
  • Task Scheduling: Detecting whether a set of tasks with prerequisites can be completed
  • Alien Dictionary: Reconstructing an unknown ordering from sorted data
  • Dijkstra's Algorithm: Finding shortest paths in graphs with non-negative edge weights
  • Minimum Spanning Tree: Connecting all vertices with minimum total edge weight

Chapter Roadmap

Click any topic to jump in

Interactive demo
1
Topological Sort

Linear ordering of a DAG so every edge points forward — via Kahn's BFS or reverse DFS postorder.

Kahn's Algorithm (BFS-Based)DFS-Based Topological Sort
Scheduling and cycle detection
2
Task Scheduling

Cycle detection and Course Schedule — topological sort's most famous application.

Cycle Detection in Directed GraphsCourse Schedule Ordering
Ordering problems across domains
3
Alien Dictionary

Extract character ordering from sorted words — build a DAG, then topo-sort it.

Extracting Ordering from Sorted WordsBuilding and Sorting the Character DAG
From unweighted to weighted
4
Dijkstra's Algorithm

Greedy shortest path in weighted graphs — priority queue + edge relaxation.

Relaxation and the Priority QueuePath Reconstruction
Optimal spanning structures
5
Minimum Spanning Tree

Connect all nodes at minimum cost — Kruskal with Union-Find or Prim with a heap.

Kruskal's Algorithm with Union-FindPrim's Algorithm

Topics

5 topics in this chapter

A build system must compile a library before every program that imports it, a spreadsheet must recompute a cell before every formula that reads it, and a package manager must install dependencies before the packages that need them. Each problem is a set of tasks plus "must come before" rules, and the question is the same: in what order can the tasks run so that no task starts before its prerequisites?

The previous chapter, Graphs, ended with Word Ladder, a BFS over an undirected implicit graph. Ordering problems need directed edges: an edge u→vu \to v means uu must come before vv. A topological sort lists the vertices so that every edge points forward. Such an order exists exactly when the graph has no directed cycle, a directed acyclic graph or DAG, because a cycle would require a task to come before itself.

We first build Kahn's algorithm, which repeatedly removes a vertex that no remaining edge points into, using in-degree counts and a queue. Then we derive the DFS method, which lists vertices in reverse order of when their searches finish, and compare what each approach reveals when the graph does contain a cycle.

Definition

A topological sort of a directed graph G=(V,E)G = (V, E) is a linear ordering of its vertices such that for every edge u→vu \to v, uu comes before vv. It exists if and only if GG is acyclic, and is usually not unique. Kahn's algorithm and DFS finishing order each compute one in O(V+E)O(V + E) time.

In this topic

  1. 1Kahn's Algorithm (BFS-Based)
  2. 2DFS-Based Topological Sort
1 of 2
Kahn's Algorithm (BFS-Based)

Kahn's algorithm works by repeatedly removing vertices with in-degree 0 (no incoming edges). Start by computing the in-degree of every vertex. Add all vertices with in-degree 0 to a queue. Process each vertex from the queue: add it to the result, then decrement the in-degree of all its neighbors. If a neighbor's in-degree drops to 0, enqueue it.

If the result contains all VV vertices, the ordering is valid. If fewer than VV vertices are processed, the graph contains a cycle and no topological order exists.

Time: O(V+E)O(V + E) --- each vertex and edge processed once. Space: O(V)O(V) for the queue and in-degree array.

Mathematical Intuition

Kahn's algorithm produces a topological order by repeatedly removing vertices with in-degree 0. Start by computing in-degrees in O(V+E)O(V + E), enqueue all zero-in-degree vertices, then repeatedly dequeue uu, append to result, and decrement in-degrees of uu's successors; enqueue any that drop to 0. Total time is O(V+E)O(V + E) because each edge is processed once (decrement) and each vertex is enqueued/dequeued once. If the final result has fewer than VV vertices, the graph has a cycle — Kahn's naturally detects this.

Example:

Given a DAG with edges: 5->0, 5->2, 4->0, 4->1, 2->3, 3->1. Find a topological ordering using Kahn's algorithm.

2 of 2
DFS-Based Topological Sort

The DFS approach performs a depth-first traversal and records each vertex's finish time. When a DFS call finishes processing a vertex (all descendants explored), the vertex is pushed onto a stack (or prepended to a list). The final stack order, read top to bottom, is a valid topological sort.

The intuition is that a vertex finishes after all vertices it can reach have finished --- so it belongs earlier in the ordering. This method naturally handles disconnected DAGs by running DFS from each unvisited vertex.

Time: O(V+E)O(V + E). Space: O(V)O(V) for the recursion stack and visited set.

Mathematical Intuition

DFS-based topo sort computes the postorder of a DFS traversal, then reverses it. The key insight: when DFS finishes processing a vertex uu (all descendants done), uu's postorder timestamp is later than all its descendants'. Reversing puts uu before its descendants, which is exactly the topological requirement. Time is O(V+E)O(V + E). To detect cycles, track vertices in three states: white (unvisited), gray (on stack), black (finished). Encountering a gray vertex means a back edge — a cycle.

Example:

Run DFS-based topological sort on the same graph: 5->0, 5->2, 4->0, 4->1, 2->3, 3->1. Start DFS from vertex 5, then 4.