Depth-First Search & Listener Circles
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).

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:
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:
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.
What remembers where to come back to? The call stack — each visit waiting
for a deeper one to return is a frame on it:
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).
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:
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:
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:
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 component search: one DFS per unvisited listener, and each search paints exactly one circle.