Skip to the workspace
Pebellslearn by building
Graphs  ›  Lesson

Depth-First Search & Listener Circles

Depth First Search 24 minFollowing one path as far as it goes

dsa / Depth-First Search & Listener Circles

Explore each scene at your own pace.

01 · Tunebox's listener circles

Tunebox's listener circles

Depth-First Search & Listener Circles

Definition
Depth-first search explores a graph by following one path as deep as it can go, then backing up to the last unexplored branch, using recursion or a stack and a visited set so no vertex is processed twice.
In plain words
Picture exploring a maze by always taking the first unexplored corridor until you hit a dead end, then walking back to the last junction with a path you have not tried. You only turn round when you have nowhere new to go.

In short: depth-first search (DFS) goes as deep as possible down one path before backing up and trying the next — the opposite order from BFS's rings. Recursion does it for free (the call stack remembers where to come back to), or you can hold an explicit stack yourself. The same walk finds every connected component, detects cycles, and puts "must happen before" steps into a safe topological order. Cost: O(V + E) time, O(V) memory for the visited set plus the stack (or call stack).

A corridor diagram: ana goes deep to ben, then deeper to dia which is a dead end, backs up to ben, backs up to ana, and only then tries ana's second friend cal

Tunebox's listener circles

Tunebox's Circles tab groups friends linked directly or through a chain, so each circle can share a blend playlist. Recursion is the natural way to write DFS: visit a listener, then — before looking at anyone else — visit their first friend, and that friend's first friend, and so on:

python

Each badge below is the recursion depth at which that listener was visited — the walk finishes Ben's whole branch, including Dia, before it ever looks at Cal:

watch it move · graph

DFS finishes one whole branch before it tries the next, backing up only at a dead end.

visit(ana) is the first call, at depth 0. 4 nodes, 3 edges, undirected. At ana. Frontier: ana. ana: 0.

1 / 8

What remembers where to come back to? The call stack — each visit waiting for a deeper one to return is a frame on it:

watch it move · stack

The call stack grows as the walk goes deeper and shrinks as it backs up.

One frame: visit(ana) is running. Stack, 1 item. Top is visit(ana).

1 / 7

The mistake: skipping the visited set because a small test graph happens to have no loops. Real friendships always loop back — Ana lists Ben and Ben lists Ana — and without a visited set the calls never stop:

What happens when this runs?
graph = {"ana": ["ben"], "ben": ["ana"]}

def dfs(name):
    for nxt in graph[name]:
        dfs(nxt)

dfs("ana")
print("done")

You can hold that stack yourself instead of relying on Python's — a list you append to and pop from, immune to the recursion limit. Two details make it visit in exactly the recursive order: push neighbours in reverse so the first-listed one is popped next, and check seen when you pop, because a listener may be pushed more than once before its turn comes:

python

One DFS finds everyone reachable from one listener — their connected component, or circle. To find every circle, loop over all listeners and start a fresh DFS from each one nobody has visited yet:

step through it
1graph = {"ana": ["ben"], "ben": ["ana"], "cal": [], "dia": ["eli"], "eli": ["dia"]}
2seen, circles = set(), []
3for name in graph:
4 if name in seen:
5 continue
6 circle, stack = [], [name]
7 seen.add(name)
8 while stack:
9 current = stack.pop()
10 circle.append(current)
11 for friend in graph[current]:
12 if friend not in seen:
13 seen.add(friend)
14 stack.append(friend)
15 circles.append(circle)
16print(circles)

Every listener is visited exactly once across all the searches, so the whole thing stays O(V + E). Here are the circles forming — each badge is the circle number that listener joined:

your code, drawn · graph

Your component search: one DFS per unvisited listener, and each search paints exactly one circle.

Scene 1 of 6
Project context and further resources
You're building a piece ofTunebox — recommendations
This piece — listener_circles(): Finds groups of listeners connected to each other.
Scenario Tunebox's Circles tab groups friends who are linked to each other, directly or through someone else, so each group can share a blend playlist.
listener_circles.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
listener_circles(graph) → listEvery circle of connected listeners, each sorted, ordered by first name.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.