BFS
topological sort
graph algorithms
computer science
data structures

Relationship between BFS and topological sort

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Breadth-first search and topological sort are different algorithms with different goals, but they are related in one important way: one of the standard topological sort algorithms, Kahn's algorithm, uses a queue-driven process that looks a lot like BFS.

That similarity often causes confusion. Topological sort is not just "BFS on a directed graph," but BFS ideas do help explain how one topological ordering method works.

What BFS Does

BFS explores a graph level by level from a chosen starting node. In an unweighted graph, it is useful for shortest-path distances measured in number of edges.

Typical BFS:

python
1from collections import deque
2
3def bfs(graph, start):
4    visited = {start}
5    queue = deque([start])
6    order = []
7
8    while queue:
9        node = queue.popleft()
10        order.append(node)
11
12        for neighbor in graph[node]:
13            if neighbor not in visited:
14                visited.add(neighbor)
15                queue.append(neighbor)
16
17    return order
18
19
20graph = {
21    "A": ["B", "C"],
22    "B": ["D"],
23    "C": ["D"],
24    "D": [],
25}
26
27print(bfs(graph, "A"))

The purpose here is traversal from a source. The order depends on the start node and adjacency layout.

What Topological Sort Does

Topological sort applies only to a directed acyclic graph, or DAG. It returns an ordering where every directed edge goes from earlier to later in the sequence.

If there is an edge from A to B, then A must appear before B.

That makes topological sort useful for dependency problems such as:

  • course prerequisites
  • build systems
  • job scheduling
  • pipeline execution

Unlike BFS, topological sort is not about levels from one source. It is about respecting dependency direction across the whole graph.

Where the BFS Connection Comes In

Kahn's algorithm for topological sort uses:

  • an indegree count for every node
  • a queue of nodes whose indegree is zero
  • repeated removal of ready nodes from the queue

That queue processing feels similar to BFS because both algorithms repeatedly pop from a queue and push new nodes discovered through outgoing edges.

Here is Kahn's algorithm:

python
1from collections import deque
2
3def topological_sort(graph):
4    indegree = {node: 0 for node in graph}
5
6    for node in graph:
7        for neighbor in graph[node]:
8            indegree[neighbor] += 1
9
10    queue = deque([node for node in graph if indegree[node] == 0])
11    order = []
12
13    while queue:
14        node = queue.popleft()
15        order.append(node)
16
17        for neighbor in graph[node]:
18            indegree[neighbor] -= 1
19            if indegree[neighbor] == 0:
20                queue.append(neighbor)
21
22    if len(order) != len(graph):
23        raise ValueError("Graph contains a cycle")
24
25    return order
26
27
28dag = {
29    "cook": ["eat"],
30    "shop": ["cook"],
31    "set_table": ["eat"],
32    "eat": [],
33}
34
35print(topological_sort(dag))

This looks BFS-like because of the queue, but the selection rule is different. Nodes enter the queue when all prerequisites are satisfied, not because they are one edge farther from a source.

The Key Difference

BFS uses reachability from a starting node.

Topological sort uses dependency constraints across the entire DAG.

That means:

  • BFS can run on cyclic graphs
  • topological sort requires an acyclic directed graph
  • BFS order does not necessarily satisfy dependency rules
  • topological order does not necessarily reflect shortest-path layers

A BFS traversal of a DAG may accidentally produce a valid topological order in some graphs, but that is not guaranteed.

Example Showing the Difference

Consider this graph:

python
1graph = {
2    "A": ["C"],
3    "B": ["C"],
4    "C": [],
5}

Valid topological orders include:

  • 'A, B, C'
  • 'B, A, C'

But BFS from A only visits nodes reachable from A in source order:

python
print(bfs(graph, "A"))  # ['A', 'C']

That is not even a full topological ordering of the graph, because B was never part of the traversal from source A.

This example shows why BFS and topological sort solve fundamentally different problems.

DFS-Based Topological Sort Also Exists

Topological sort can also be implemented with depth-first search by pushing nodes onto a stack after exploring all outgoing edges. That version has no obvious BFS flavor at all.

So the relationship is not "topological sort comes from BFS." The more accurate statement is:

Kahn's algorithm uses a queue-based process that resembles BFS, but topological sorting itself is a distinct graph problem.

Common Pitfalls

The biggest pitfall is calling a BFS traversal a topological sort just because both can use a queue. The queue is not the defining property.

Another issue is forgetting that topological sort only exists for DAGs. If the graph has a cycle, no valid topological order exists.

Developers also sometimes think BFS levels correspond to dependency order. They can overlap in certain DAGs, but the concepts are not interchangeable.

Finally, do not assume the result of topological sort is unique. Many DAGs have multiple valid topological orders.

Summary

  • BFS and topological sort are different algorithms with different goals.
  • Kahn's topological sort resembles BFS because it uses a queue.
  • BFS explores from a start node, while topological sort respects dependency order across a DAG.
  • A BFS order is not guaranteed to be a valid topological order.
  • Topological sort is defined only for directed acyclic graphs.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.