Programming Fundamentals · Search and Decision

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.

Maze personality test · one map, two ways

🏁 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?

Run BFS first—watch the ripple spread
BFS · ripple layer sweep
cells visited
final path length
DFS · single-head snake dive
cells visited
final path length
Two numbers teach the whole theory. BFS visits 77 cells before hitting the goal—it floods every cell at distance 1, 2, 3… from the start, so that whole sheet must live in memory; but because it advances by distance, the path that first hits the goal is always shortest (23 cells). DFS reaches it after only 44 visits, keeping just the current path in memory; yet its path is 37 cells—more than half longer than shortest—and unlucky runs dive into dead ends and back out (faded cells are backtracking).
What does this have to do with AI?

Swap maze cells for folders and web pages—and both personalities show up next to you:

Neither wins everywhere—only fit to the scene. Need “shortest / nearest / most relevant”? BFS, pay the memory. Need “any usable answer fast, memory tight”? DFS, accept detours. Next lesson’s greedy and sampling, then Beam Search, are also picking spots on this “search-strategy spectrum.”

What this lesson wants to share