Recognition guide
DFS vs BFS: how to tell which one a problem needs
Depth-first search (DFS) and breadth-first search (BFS) visit the same nodes. On a graph, tree, or grid they cost the same: O(n + e) time, where n is the number of nodes and e the number of edges. The only difference is the order, so the real question is whether the problem's answer depends on that order.
This guide is about that decision. It does not re-teach either algorithm. For that, read the Depth-First Search and Breadth-First Search pattern pages. Here you learn what to look for in the problem statement before you write a line of code.
The one-sentence test
Ask what the answer is measured in.
- If it is measured in distance or rounds (how many steps, which level, how long until everything is reached), you want BFS.
- If it is measured in structure (what is below this node, which nodes belong together, every way to do something), you want DFS.
- If it is only membership (can I reach it, how many separate groups), either works.
Signals that point to BFS
BFS keeps a frontier: everything at the same distance from the start. These phrases mean the frontier matters.
- "Shortest", "fewest", "minimum number of steps/moves/edges." On a graph where every step costs the same, the first time BFS reaches a node is the shortest way there.
- "Level by level", "row by row", "each depth". The statement already groups nodes by distance from the root.
- "Nearest", "closest", "spreads each minute/round/day." Anything that expands outward in lockstep is a frontier.
- "Every move costs one." A letter change, a knight's move, one grid step. Equal costs are what make a plain queue correct.
Signals that point to DFS
DFS follows one branch to its end, then backs up. These phrases mean a whole branch or path is the unit of work.
- "Subtree", "ancestor", "left and right child." The answer for a node is built from the answers for its children.
- "All paths", "every combination", "list all." You must walk each path to its end, and you need to undo a choice before the next one.
- "Cycle", "valid ordering", "connected pieces." You are asking about the structure of the graph, not distances in it.
- "Copy", "clone", "serialize." Each node is handled once, children included.
When either works
Many statements only ask whether things are connected: "count the islands", "is there any path from A to B", "flood-fill this region". Nothing in the answer depends on order, so both are correct. Pick the one that is easier to write without a bug. DFS is usually shorter with recursion. BFS is safer when the structure can be very deep, because a recursive DFS on a million-cell snake can overflow the call stack.
Counter-signals
These look like a reason to pick one and are not.
- "Find a path" does not mean shortest. If the statement never says shortest, fewest, or minimum, any path is acceptable and DFS is fine.
- "Tree" does not mean DFS. A tree with a "by level" requirement is a BFS problem.
- "Weighted" or "cost" with different values per edge means neither plain version works. The first arrival is no longer the cheapest, so you need a cheapest-first search that uses a heap.
- "Sorted" with a single value to look up is usually binary search, not a graph walk.
The decision checklist
- Does the statement ask for a distance, a number of steps, or a round? If every step costs the same, use BFS.
- Does it want results grouped by level or by distance from a start? Use BFS.
- Does it combine results from children, list every path, or need an undo step? Use DFS.
- Is it only about which nodes belong together or whether something is reachable? Either; choose by depth risk and by what you can write cleanly.
- Do the steps have different costs? Neither plain version. Use a heap-based search.
The only line that really differs
Here is a walk over a graph. Only one expression changes between the two searches: which end of the open list you take the next node from.
function walk(start: Node, useQueue: boolean): void {const seen = new Set<Node>([start]);const open: Node[] = [start];while (open.length > 0) {// Oldest first = breadth-first. Newest first = depth-first.const node = useQueue ? open.shift()! : open.pop()!;for (const next of node.neighbors) {if (!seen.has(next)) {seen.add(next); // mark when discovered, not when takenopen.push(next);}}}}
shift() on a long array is slow.Three worked examples
1. "Given a grid of 0s and 1s, count the islands of connected 1s."
Clue: "connected" and "count". Nothing asks how far apart cells are. This is membership, so either search works. DFS is the shorter choice: flood each unseen 1 and add one to the count.
Pattern: DFS (BFS is also correct).
2. "Change one letter at a time, using only words from a list. Return the length of the shortest sequence from the start word to the end word."
Clue: "shortest", and every change costs one. The words are nodes, and the first time BFS reaches the end word is the minimum. DFS would find a sequence, then have to compare it against all the others.
Pattern: BFS.
3. "Return every root-to-leaf path in a binary tree whose values add up to a target."
Clue: "every path". You carry the running path and sum down each branch, record it at a leaf, and undo the last step on the way back. A frontier of same-depth nodes does not help here.
Pattern: DFS.
Common traps
- Using DFS for the shortest path on an unweighted graph. It returns a valid path that is often a long detour.
- Marking a node seen only when you take it from the list. Two neighbors can add the same node, and counts or copies come out wrong. Mark it when you discover it.
- Mixing levels in BFS. If you need "per level" output, note the queue size before you add anyone new. That many nodes belong to the current level.
- Treating different edge costs as equal. A cheap long route can beat an expensive short one. A plain queue cannot see that.
- Forgetting recursion depth. DFS on a very deep input needs an explicit stack, or the program may crash.
Quick answers
Can DFS find the shortest path?
On an unweighted graph it can, but only by exploring every path and comparing, which is more work than BFS. If the statement says shortest or fewest, start with BFS.
Which one uses less memory?
BFS holds one frontier, which can be as wide as the graph. DFS holds one path, which can be as deep as the graph. Which is smaller depends on the shape of the input.
Does it matter on a tree?
Only when the answer depends on level or on a branch result. For a plain "visit every node", both are fine.
Practice it on Algofily
Recognizing the pattern is a skill on its own, so Algofily trains it before you write code. Each problem moves through Understand, Think, Code, and Explain. In the Code stage, Algofily AI can give progressive hints (sign-in required).
- Read the Depth-First Search pattern page and the Breadth-First Search pattern page for worked examples and problems that practice each.
While you code, Algofily AI can ask a question and open the next hint.