Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
Depth-first search walks a graph like a maze: follow one corridor as far as it goes, step back at a dead end, and chalk a tick in every room. Emma's friend network step by step, the recursive Python walk, and why a row of ten thousand people crashes it.
What you will learn
- Explain how DFS goes as deep as it can and backs up at a dead end
- Write a recursive DFS with a visited set, and say why the set is needed
- Explain why a very deep graph causes a RecursionError
- Compare DFS with BFS: same O(V + E) cost, different order and uses
Before you start
- Graphs as adjacency lists and BFS
- Recursion and the call stack
These are Emma's friends again, the same six people as in graphs and breadth-first search. Emma knows Jack and Tom. Jack knows Kate and Tom. Tom knows Lucy, who knows Mark. This time we walk differently. Follow one friend, then that friend's friend, then theirs, as deep as you can. Stuck? Step back one friend and try the next one. Going deep first is called depth-first search, or DFS.
Walking a maze
Imagine a maze. The rooms are joined by corridors, and we start in room Emma. We walk deep: Emma, then Jack, then Kate. Kate's room is a dead end, so we walk back to Jack and try his next corridor: Tom, then Lucy, then Mark.
One more trick: we chalk a tick in every room we visit. Emma, Jack and Tom make a loop, and without the ticks we'd go round and round forever. In Python, going deeper means calling the function again, backing up means returning, and the ticks are a visited set.
DFS in Python
The graph is the same adjacency list as before: one list of friends per person, each friendship added both ways, and of(who) giving a person's friends in the order they were added. Only the walk is new:
show = True
visited = set()
def walk(g, who, depth):
visited.add(who)
if show:
print(" " * depth + "visit " + who)
for f in g.of(who):
if f not in visited:
walk(g, f, depth + 1) # go deeper
# no new friend: back up
visited is the chalk ticks. walk marks this person, prints the name with two spaces per level, then, for each friend not visited yet, calls itself one level deeper. When no new friend is left, the function simply ends, and we back up. Python's call stack remembers the way back.
from friends import Friends
import dfs
friends = Friends()
friends.add("Emma", "Jack")
friends.add("Emma", "Tom")
friends.add("Jack", "Kate")
friends.add("Jack", "Tom")
friends.add("Tom", "Lucy")
friends.add("Lucy", "Mark")
dfs.walk(friends, "Emma", 0)
print("people reached: " + str(len(dfs.visited)))
visit Emma
visit Jack
visit Kate
visit Tom
visit Lucy
visit Mark
people reached: 6
Tom lines up with Kate. That's because we backed up to Jack in between, and Tom is Jack's next friend at the same depth.
Step by step
| Now at | What happens | Call stack (way back) |
|---|---|---|
| Emma | tick; Jack is new, go deeper | Emma |
| Jack | Emma ticked, skip; Kate is new, go deeper | Emma, Jack |
| Kate | only friend Jack is ticked: dead end, back up | Emma, Jack, Kate |
| Jack | next friend Tom is new, go deeper | Emma, Jack |
| Tom | Emma, Jack ticked; Lucy is new | Emma, Jack, Tom |
| Lucy | Tom ticked; Mark is new | Emma, Jack, Tom, Lucy |
| Mark | only friend Lucy ticked: dead end | Emma, Jack, Tom, Lucy, Mark |
| back up | Lucy, Tom, Jack have nothing new; Emma's last friend Tom is ticked | empty, done |
Why the ticks matter
Without them, look at the loop: Emma to Jack, then Tom, and Tom is a friend of Emma, so back to Emma, and it all starts again. With the ticks, at Tom we see Emma and Jack already ticked, skip them, and go on to Lucy. Before you walk into a room, look for a tick. That's why nobody is visited twice and the walk always ends.
Far too deep
What's the worst case for going deep? A very long row, where everyone knows only the next person.
from friends import Friends
import dfs
dfs.show = False
for n in (100, 500, 10_000):
chain = Friends()
for i in range(1, n): # one long row
chain.add("user" + str(i - 1), "user" + str(i))
dfs.visited.clear()
dfs.walk(chain, "user0", 0)
print(f"{n:7,d} in a row: reached {len(dfs.visited):,}")
Output, with the long middle of the traceback cut:
100 in a row: reached 100
500 in a row: reached 500
Traceback (most recent call last):
...
[Previous line repeated 995 more times]
...
RecursionError: maximum recursion depth exceeded
Every step deeper adds one more call waiting on the stack, and calls only leave when we back up. A hundred is fine, five hundred is fine, but ten thousand fills the stack. Think of a pile of waiting jobs with limited room: once it's full, the program gives up. Programs that go very deep keep their own stack instead, for example a deque, and loop instead of calling themselves.
What it costs
| Step | Cost |
|---|---|
Check for a tick (in visited) | O(1) |
| Visit every person | once each, O(V) |
| Check every friendship | from both ends, O(E) |
| Whole DFS | O(V + E) |
| Stack space | one call per level of depth |
That's the same cost as BFS; only the order differs. Six people and six friendships give six visits and twelve checks. A million people with three million friendships give a million visits and six million checks. One more watch-out: DFS reaches everyone, but the way it finds isn't always the shortest. It reaches Mark in four steps (Jack, Tom, Lucy, Mark), but three is possible, straight through Tom. For fewest hops, use BFS.
Where you meet DFS
- Solving a maze or puzzle: try one way as far as it goes, step back at a dead end.
- Searching folders: open a folder, then the folder inside it, back up when done.
- Checking who is connected: walk from one computer and see who you reach. Anyone left out is cut off.
- Putting jobs in order when some need others done first.
Try it yourself
Start the walk from Mark instead of Emma. Guess the visit order first, then run it and check.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
