Depth-first search (DFS) in Python, visualized step by step
PythonC
From the start, keep following an unvisited neighbour deeper and deeper; at a dead end, go back to the previous vertex and try its next neighbour. The recursion itself remembers where you came from.
dfs.py
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D", "E"],
"D": ["F"],
"E": ["F"],
"F": [],
}
seen = set()
order = []
def dfs(v):
seen.add(v)
order.append(v)
for w in graph[v]:
if w not in seen:
dfs(w)
dfs("A")
print(order)
How Depth-first search (DFS) works
- Arrive at v: mark it seen and record it.
- Look at v's neighbours w in turn.
- If w is not seen yet, recurse into w and keep going deeper.
- When all of v's neighbours are done, the call returns to the previous vertex.
What to watch
The call stackOne level more for each vertex deeper, one less on the way back.
The orderA → B → D → F all the way down before it comes back for C and E.
FAQ
What is the time complexity of DFS?
O(V + E): each vertex is visited once and each edge looked at once.
What if the recursion gets too deep?
On a big graph the call stack can overflow (Python raises RecursionError). Write it with your own stack instead.
What is DFS used for?
Connected components, cycle detection, topological sort, mazes, and backtracking (permutations, combinations).