Skip to content

BFS and DFS: same graph, different order

BasicsUnder the hood

Breadth-first and depth-first search visit the same nodes. Swap a queue for a stack and the order changes completely: one spreads out in rings, the other dives down a single path.

01 One loop, one line apart

Both searches keep a collection of nodes waiting to be visited. Each turn takes one out, visits it, and adds its neighbours. The only question is which waiting node comes out next: the oldest (a queue, first in first out) or the newest (a stack, last in first out).

Breadth-first
from collections import deque
def bfs(graph, start):
seen, order = set(), []
todo = deque([start])
while todo:
node = todo.popleft()
if node in seen:
continue
seen.add(node)
order.append(node)
for nxt in graph[node]:
if nxt not in seen:
todo.append(nxt)
return order
Depth-first
from collections import deque
def dfs(graph, start):
seen, order = set(), []
todo = deque([start])
while todo:
node = todo.pop()
if node in seen:
continue
seen.add(node)
order.append(node)
for nxt in graph[node]:
if nxt not in seen:
todo.append(nxt)
return order

A deque takes items from either end, so the two functions differ in one call. Both mark a node as seen when it comes out. That keeps them identical, at a cost you will see in the traces: a node can wait in the collection twice.

02 Breadth-first: the queue spreads in rings

Here is the graph, drawn with A at the top and each row one edge further away. Neighbours are listed alphabetically.

BFS from A
Step 1 of 9
Graph
A
B
C
D
E
F
Queue · front first
Empty
Visit order
Empty
  • not reached
  • just added
  • waiting
  • taken out and visited
  • visited

Nothing has run yet. The queue is empty and no node is visited.

0 visited

The visit order is A, then everything one edge away, then everything two edges away. A queue serves nodes in the order they were found, and nodes are found ring by ring. That is why the first time BFS reaches a node, it has used the fewest edges possible.

03 Depth-first: the stack dives

Same graph, same loop, pop() instead of popleft().

DFS from A
Step 1 of 9
Graph
A
B
C
D
E
F
Stack · top is taken next
Empty
Visit order
Empty
  • not reached
  • just added
  • waiting
  • taken out and visited
  • visited

Nothing has run yet. The stack is empty and no node is visited.

0 visited

The order A C F E B D is one long path. The stack always serves the newest node, which is a neighbour of the node just visited, so the walk keeps going deeper until it reaches a dead end. Only then does it fall back to older entries.

It went right first because C was pushed last. Push neighbours in reverse (reversed(graph[node])) if you want B first; then the order matches a recursive DFS that loops over neighbours alphabetically: A B D E F C.

04 Rings vs a single path

main.py
graph = {
"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"],
"D": ["B"], "E": ["B", "F"], "F": ["C", "E"],
}
print(bfs(graph, "A"))
print(dfs(graph, "A"))
Text
['A', 'B', 'C', 'D', 'E', 'F']
['A', 'C', 'F', 'E', 'B', 'D']
BFS · queueNearest firstVisits by distance from the start. Use it for the fewest moves, the fewest minutes, or anything measured in levels. Memory grows with the widest ring.
DFS · stackOne branch to the endFinishes a path before trying another. Use it to explore everything, flood an area, or find cycles. Recursion is the usual way to write it; memory grows with the longest path.

Both visit every reachable node once and look at every edge from both ends, so both take O(V + E) time with an adjacency list. To count separate groups, such as islands, run either one from every node that is not seen yet and count how many times you start.

05 A grid is a graph too

In grid problems each cell is a node, and its edges go to the four cells beside it. You never build an adjacency list: you work out the neighbours with (r + dr, c + dc) and check they are in bounds.

Rotting oranges is BFS with several starts. Put every rotten orange in the queue first. The queue then spreads from all of them at once, and each ring is one minute.

Minute each orange rots, spreading from two rotten oranges
3 × 4 crate
0123
00123
112
22210
  • rotten at minute 0
  • fresh orange
  • empty cell

Every number is one more than a neighbour's number. The answer is the largest one: 3 minutes.

oranges.py
from collections import deque
def minutes_to_rot(grid):
rows, cols = len(grid), len(grid[0])
todo = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
todo.append((r, c, 0)) # every rotten orange starts at once
minutes = 0
while todo:
r, c, t = todo.popleft()
minutes = max(minutes, t)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
r2, c2 = r + dr, c + dc
if 0 <= r2 < rows and 0 <= c2 < cols and grid[r2][c2] == 1:

06 When it bites

seen.add(node) # after popleftMarking BFS lateMarking on the way out lets a node enter the queue several times, as F did. For BFS, mark it when you add it, so each node is queued once. On a large grid this is the difference between passing and running out of time.
seen.add(nxt); todo.append(nxt)Marking DFS earlyWith a stack, marking on push still visits everything, but the order is no longer depth-first: a node is claimed by whoever pushed it first, not by the path that reaches it first. Mark on pop, or use recursion.
while todo: ...No seen setOn a graph with a cycle, A adds B, B adds A, and the loop never ends. Trees are the only graphs where you can skip it.
RecursionErrorRecursive DFS on a long pathCPython's default recursion limit is about 1,000 frames. A 100 × 100 grid can contain a path of thousands of cells. Use an explicit stack.
BFS on weighted edgesFewest edges is not lowest cost when edges have different weights. Plain BFS gives the shortest path only when every edge costs the same; otherwise use Dijkstra's algorithm.

07 Check yourself

Question

You swap popleft() for pop() in the BFS above. What changes?

Question

You need the fewest moves from the entrance of a maze to its exit. Every move costs the same. Which search?

Question

In the BFS trace, why did F enter the queue twice?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?