Breadth-First Search and Depth-First Search in Python
Almost every graph algorithm starts by walking the graph. Breadth-first search (BFS) and depth-first search (DFS) are the two basic ways to do it. They visit the same vertices and differ only in the order, and that order is what makes each one useful: BFS finds shortest paths in unweighted graphs, and DFS is the engine behind connected components, cycle detection and topological sort.
This guide assumes you know what an adjacency list is. If not, read graphs and graph representations first. Examples use Python 3.10 or later and only the standard library.
The example graph
All examples use one small undirected graph stored as an adjacency list: a dict mapping each vertex to the list of its neighbors. A-B, A-C, B-D, C-D, C-E, D-F and E-F are its seven edges, so V = 6 and E = 7. Because the graph is undirected, each edge appears in two lists.
Breadth-first search
BFS explores in rings. It visits the start, then every vertex one edge away, then every vertex two edges away, and so on. A FIFO queue produces exactly that order: vertices are taken from the front and their unvisited neighbors join at the back. In Python the queue is a collections.deque, whose popleft is O(1); list.pop(0) would shift every element and cost O(n) per call.
from collections import deque
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D", "E"],
"D": ["B", "C", "F"],
"E": ["C", "F"],
"F": ["D", "E"],
}
def bfs_distances(graph, start):
dist = {start: 0}
parent = {start: None}
queue = deque([start])
while queue:
u = queue.popleft()
for v in graph[u]:
if v not in dist: # mark when enqueued
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
return dist, parent
def path_to(parent, target):
path = []
while target is not None:
path.append(target)
target = parent[target]
return path[::-1]
dist, parent = bfs_distances(graph, "A")
print(dist)
print(path_to(parent, "F"))
Output:
{'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}
['A', 'B', 'D', 'F']
The dist dict is the number of edges on a shortest path from A to each vertex, and the parent map lets you rebuild one such path by walking backward from the target. A to F takes three edges; A, B, D, F is one of the shortest routes (A, C, D, F and A, C, E, F are the same length).
Why BFS gives shortest paths
The queue holds vertices in nondecreasing order of distance: everything at distance k is dequeued before anything at distance k + 1 is. So the first time BFS reaches a vertex, it has reached it along a path with the fewest possible edges, and that distance never needs correcting.
That argument counts edges, not weights. If edges have different lengths, the path with the fewest edges may not be the cheapest one. For non-negative weights, use Dijkstra's algorithm, which replaces the queue with a priority queue.
Mark a vertex when you enqueue it
The code adds a vertex to dist at the moment it is put in the queue, not when it is taken out. If you wait until dequeue, a vertex with several already-visited neighbors can be enqueued once per neighbor. In the graph below, E is adjacent to B, C and D, all of which are processed before E is dequeued:
from collections import deque
graph = {
"A": ["B", "C", "D"],
"B": ["A", "E"],
"C": ["A", "E"],
"D": ["A", "E"],
"E": ["B", "C", "D"],
}
def enqueues(graph, start, mark_on_enqueue):
visited = {start}
queue = deque([start])
pushes = 1
while queue:
u = queue.popleft()
if not mark_on_enqueue:
visited.add(u)
for v in graph[u]:
if v not in visited:
if mark_on_enqueue:
visited.add(v)
queue.append(v)
pushes += 1
return pushes
print("mark on enqueue:", enqueues(graph, "A", True))
print("mark on dequeue:", enqueues(graph, "A", False))
mark on enqueue: 5
mark on dequeue: 7
Marking on enqueue puts each of the five vertices in the queue exactly once. Marking on dequeue puts E in three times, and on a dense graph the waste grows with the number of edges. It also breaks the "first time reached is shortest" reasoning unless you add a second check.
Depth-first search
DFS goes as deep as it can along one path, and only backs up when it reaches a vertex with no unvisited neighbors. Recursion does the backing up for you, because the call stack remembers where to return:
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D", "E"],
"D": ["B", "C", "F"],
"E": ["C", "F"],
"F": ["D", "E"],
}
def dfs_recursive(graph, u, visited=None, order=None):
if visited is None:
visited, order = set(), []
visited.add(u)
order.append(u)
for v in graph[u]:
if v not in visited:
dfs_recursive(graph, v, visited, order)
return order
def dfs_iterative(graph, start):
visited, order = set(), []
stack = [start]
while stack:
u = stack.pop()
if u in visited:
continue
visited.add(u)
order.append(u)
for v in reversed(graph[u]): # reversed: same order as recursion
if v not in visited:
stack.append(v)
return order
print(dfs_recursive(graph, "A"))
print(dfs_iterative(graph, "A"))
['A', 'B', 'D', 'C', 'E', 'F']
['A', 'B', 'D', 'C', 'E', 'F']
The iterative version replaces the call stack with an explicit list used as a stack. Two details matter. First, a vertex can be pushed more than once before it is popped, so the code skips it on pop if it is already visited; this variant can hold up to O(E) entries on the stack. Second, pushing neighbors in reverse order makes the stack pop them in the same order the recursion would visit them, which is why both lines of output match. Either neighbor order gives a valid DFS; the reversal only makes the two versions easy to compare.
Prefer the iterative form for large graphs. Python's default recursion limit is 1000 (sys.getrecursionlimit()), and a recursive DFS down a long path of vertices goes one call deeper per vertex, so a path graph with a few thousand vertices raises RecursionError. Converting to a loop is the right fix; raising the limit only moves the crash.
Running time: O(V + E)
With an adjacency list, both searches do two kinds of work:
- each vertex is marked and taken from the queue or stack once: O(V) in total;
- each vertex's neighbor list is scanned once, and the lengths of all lists add up to E for a directed graph or 2E for an undirected one: O(E) in total.
Together that is O(V + E) time, which is linear in the size of the graph. Extra space is O(V) for the visited set and the queue (the stack-with-duplicates DFS above can need O(E)), plus O(V) recursion depth for recursive DFS in the worst case.
With an adjacency matrix the bound changes. Finding a vertex's neighbors means scanning its whole row of V entries, even if only two are edges, so the total becomes O(V^2). For a sparse graph, where E is close to V, the list is much better; for a dense graph, where E is close to V^2, the two are about the same.
The Algorithm Comparison Tool lists BFS and DFS as O(n) in every case with O(n) space. Read n there as V + E, the size of the graph, as the tool's own FAQ notes. At n = 1000, in its average-case ranking, both score 1,000, the same as linear search, which is the point: a traversal is a linear scan of the graph.
Connected components with DFS
An undirected graph splits into connected components: groups of vertices joined by paths, with no edges between groups. To find them, start a traversal from every vertex that has not been seen yet; each traversal collects one component.
graph = {
1: [2], 2: [1, 3], 3: [2],
4: [5], 5: [4],
6: [],
}
def connected_components(graph):
seen, components = set(), []
for start in graph:
if start in seen:
continue
seen.add(start)
stack, comp = [start], []
while stack:
u = stack.pop()
comp.append(u)
for v in graph[u]:
if v not in seen:
seen.add(v)
stack.append(v)
components.append(sorted(comp))
return components
print(connected_components(graph))
[[1, 2, 3], [4, 5], [6]]
Vertex 6 has no edges and forms a component of its own. The outer loop touches each vertex once and the inner traversal touches each edge a constant number of times, so the whole computation is still O(V + E). Any traversal works here; BFS would find the same three groups.
What else DFS is for
- Cycle detection. In a directed graph, DFS finds a cycle when it reaches a vertex that is still "in progress" on the current path (a back edge).
- Topological sort. Listing vertices of a directed acyclic graph in reverse order of when DFS finishes them gives an order where every edge points forward. Both ideas are worked through in topological sort and cycle detection.
- Exhaustive search. Backtracking is DFS over a tree of choices instead of over a stored graph.
BFS or DFS?
| Question | Use | Why |
|---|---|---|
| Fewest edges from s to every vertex (unweighted) | BFS | Visits vertices in order of distance |
| Is t reachable from s? | Either | Both visit everything reachable |
| Connected components | Either | One traversal per component |
| Cycle in a directed graph, topological order | DFS | Needs the "in progress" state of the current path |
| Shortest path with weights | Neither | Dijkstra (non-negative weights) or Bellman-Ford |
Check yourself
- A graph is stored as an adjacency matrix with V = 1000 vertices and only 1500 edges. Roughly how many entries does BFS read? (About V^2 = 1,000,000 matrix cells, against about V + 2E = 4,000 list entries with an adjacency list.)
- Why does the BFS above never need to update a distance it has already set? (Vertices leave the queue in order of distance, so the first discovery is along a shortest path.)
- What breaks if you replace the
dequewith a stack but keep everything else? (You get a depth-first order, and the distances are no longer guaranteed to be shortest.)