← Course home

Graphs · Lesson 36 of 52

Directed acyclic graphs and topological order

Order dependency graphs and detect cycles using indegrees.

Full lessonAbout 10 min

You will learn to trace Kahn's algorithm and detect when a directed cycle prevents full ordering.

Recommended first: Graph traversals.

On this page 6 sections

The idea

Edges A to B, A to C, B to D, and C to D produce A, B, C, D.

A topological order is a list of the vertices of a directed graph such that every edge points forward in the list. topological_order on edges A to B, A to C, B to D, and C to D returns A, B, C, D. Kahn's algorithm computes an indegree for each vertex. It starts a queue with every vertex whose indegree is zero. A is the only such vertex here. When a vertex leaves the queue, each outgoing edge reduces a neighbor's indegree. A neighbor enters the queue when its indegree hits zero. B and C both become ready after A, and D waits until both of its incoming edges have been counted. has_directed_cycle on this graph is false. On a two-cycle from A to B and back, it is true, and topological_order raises ValueError. The queue runs dry before every vertex has been emitted.

A worked trace

StepStateWhat changed
Emitvertex = AEmit A. The order so far is ['A'].
Emitvertex = BEmit B. The order so far is ['A', 'B'].
Emitvertex = CEmit C. The order so far is ['A', 'B', 'C'].
Emitvertex = DEmit D. The order so far is ['A', 'B', 'C', 'D'].

Why it is correct

A vertex enters the queue only when every predecessor has already been emitted. Every edge out of an emitted vertex has been relaxed, so a later position cannot be a predecessor of an earlier one. If the graph has a cycle, some vertex on the cycle always has indegree left, because its predecessor on the cycle was never emitted. The queue empties and the output is shorter than the vertex list. That length check is the cycle test inside this function. A depth-first version records a vertex after its descendants and reverses that finish order. Both reject a back edge.

A common mistake

A directed cycle never reaches indegree zero, so the function raises.

What it costs

Each vertex is enqueued once and each edge is inspected once, so the time is proportional to vertices plus edges. Extra memory is the indegree map and the queue, proportional to the vertices. Use this order before dynamic programming on a dag, and before scheduling jobs that depend on other jobs. Do not call it on a graph that might contain a cycle unless you catch the error. The order is Θ(V + E) time and uses Θ(V) extra memory.

Run it

python
from bitsandbytes.graphs.adjacency_list import Graphfrom bitsandbytes.graphs.algorithms import topological_ordergraph = Graph()graph.add_edge('A', 'B', 1)graph.add_edge('A', 'C', 1)graph.add_edge('B', 'D', 1)graph.add_edge('C', 'D', 1)print(topological_order(graph))# prints: ['A', 'B', 'C', 'D'] 

Practice and next step

Open Shortest paths next. Shortest paths relax edges. Dijkstra needs the weights to be non-negative.

Implementation and tests Optional reference

Library code 1

  • bitsandbytes.graphs.algorithms

Use these references to compare the explanation with repository code and tests. A test link means it imports a lesson symbol; it does not by itself claim complete behavior coverage.

Step-by-step trace

Kahn's algorithm on a small dag

Edges A to B, A to C, B to D, and C to D produce the order A, B, C, D. A cycle makes topological_order raise ValueError.

vertex
A

State

  1. 0Adone

Emit A. The order so far is ['A'].

Practice feedback is loading. The lesson explanation remains available above.