BFS and DFS: same graph, different order
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).
from collections import dequedef bfs(graph, start):seen, order = set(), []todo = deque([start])while todo:node = todo.popleft()if node in seen:continueseen.add(node)order.append(node)for nxt in graph[node]:if nxt not in seen:todo.append(nxt)return order
from collections import dequedef dfs(graph, start):seen, order = set(), []todo = deque([start])while todo:node = todo.pop()if node in seen:continueseen.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.
- not reached
- just added
- waiting
- taken out and visited
- visited
Nothing has run yet. The queue is empty and no node is 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().
- not reached
- just added
- waiting
- taken out and visited
- visited
Nothing has run yet. The stack is empty and no node is 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
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.
- 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.
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.