BFS and DFS: How an Agent Finds Files in a Codebase
In the Engineering Advanced Part, a Coding Agent asked to “find why login fails” rummages through hundreds of folders. Where first—finish this layer then go deeper, or grab one clue and drill all the way? Two very different personalities: BFS (breadth-first) and DFS (depth-first). This lesson sends each through the same maze—you’ll see the personality at a glance.
🏁 is the start, 🎯 the goal, dark gray the walls. Each button is a personality—watch three things: the shape of the paint (BFS ripples in rings; DFS is a snake); the two counters below; and the final green path—whose is shorter? Who visited more cells?
BFS · ripple layer sweep
DFS · single-head snake dive
Swap maze cells for folders and web pages—and both personalities show up next to you:
Coding Agent hunting code
First ls the top level—that’s a BFS one-layer sweep for a quick global map; then auth/ looks fishy, so it dives layer by layer—switching to DFS. Real Agents use a hybrid: breadth first, then depth, plus grep jumps.
Web crawlers
From the home page, fetch every linked page first, then “links of links”—classic BFS, so near-home important pages land first. DFS might follow one chain into forum page 999 and never come back.
“Mutual friends” recommendations
“People you may know” = BFS two layers from you: layer 1 is friends; layer 2 is friends-of-friends. Someone 2 steps away ranks above someone 5 steps—depth itself is closeness.
What this lesson wants to share
- BFS layer sweep: flood by distance ring by ring—what you find is always shortest, at the cost of a big sheet in memory
- DFS go all the way down one path: saves memory, often hits a solution sooner, but paths aren’t guaranteed short—and it backtracks
- Visits vs path length: 77/23 vs 44/37—two number pairs are the full ledger of both personalities
- Real systems mix them: Agents ls one layer (BFS) then dive into a suspicious folder (DFS)
- Crawlers and mutual-friend recs are graph search—the maze is just the most intuitive graph