Breadth-first and depth-first

Two ways to walk a graph, and how the choice decides what you find first.

9 min read🧮 Data Structures and Algorithms in Java

Two ways to walk a graph, identical except for which container holds what you have not visited yet — and that one difference decides what you find first.

The same graph, two walks

A small social graph, starting from you:

plaintext
###   BFS: [you, ana, bo, cy, di, ed, fay, zoe]
###   DFS: [you, ana, di, zoe, bo, ed, cy, fay]

BFS takes everyone one step away, then everyone two steps away. ana, bo, cy — all your direct friends — before any friend-of-a-friend.

DFS commits to a path and follows it to the end: ana, then ana's friend di, then di's friend zoe, before it ever looks at bo.

Notice zoe. DFS found her fourth; BFS found her last. If the question were "find zoe", DFS won. If the question were "how far away is zoe", only BFS can answer.

The only real difference

java
// BFS — a queue
Deque<String> q = new ArrayDeque<>();
q.add(start);
while (!q.isEmpty()) {
    String v = q.poll();              // oldest first
    for (String n : neighbours(v)) if (seen.add(n)) q.add(n);
}
 
// DFS — a stack
Deque<String> st = new ArrayDeque<>();
st.push(start);
while (!st.isEmpty()) {
    String v = st.pop();              // newest first
    ...
}

poll against pop. Everything else is the same, which is why they are taught together and why ArrayDeque is the right container for both — the collections course's point about it doing both ends in O(1).

DFS also has a recursive form, and that is the more common way to write it. Its stack is the call stack, which means the previous lesson's ceiling applies: recursive DFS on a graph a hundred thousand deep overflows, and the iterative version does not.

What each one is for

BFS finds the shortest path — but only when every edge costs the same. That is the guarantee, and the condition is easy to forget. Because BFS reaches everything at distance 1 before anything at distance 2, the first time it sees a vertex is by a shortest route.

Put weights on the edges and that breaks immediately: a two-hop path can be cheaper than a one-hop path. Then you need Dijkstra, which is BFS with a PriorityQueue instead of a queue — take the cheapest frontier vertex rather than the oldest. The shape is so similar it is worth seeing as one algorithm with a different container.

DFS is for exhausting a structure, and for questions about whether a path exists rather than how long it is:

  • cycle detection
  • topological sort (build order, bean creation order)
  • connected components
  • backtracking, which is DFS over a tree of choices

The visited set is not optional

Both loops above call seen.add(n) before enqueueing. Without it, a graph with any cycle loops forever — and seen must be checked when you enqueue, not when you dequeue, or the same vertex is added many times before it is first processed.

Worth noting that this makes the traversals O(V + E): every vertex enters the container once, and every edge is looked at once.

Topological sort: an order that respects every arrow

A build has modules that depend on other modules; Spring has beans that depend on other beans; a migration has steps that must follow others. Each is a directed acyclic graph, and a topological order is any sequence in which every edge points forward — every dependency before the thing that needs it. Two algorithms, and the first is the one to write under pressure:

java
// Kahn's algorithm: peel off the nodes with nothing left to wait for
List<String> topological(Map<String, List<String>> dependsOn) {          // node -> the nodes it needs first
    Map<String, Integer> remaining = new HashMap<>();                    // how many dependencies are still unplaced
    Map<String, List<String>> dependents = new HashMap<>();              // reverse edges: who is waiting on me
    for (var e : dependsOn.entrySet()) {
        remaining.putIfAbsent(e.getKey(), 0);
        for (String dep : e.getValue()) {
            remaining.merge(e.getKey(), 1, Integer::sum);
            remaining.putIfAbsent(dep, 0);
            dependents.computeIfAbsent(dep, k -> new ArrayList<>()).add(e.getKey());
        }
    }
    Deque<String> ready = new ArrayDeque<>();
    remaining.forEach((node, count) -> { if (count == 0) ready.add(node); });
    List<String> order = new ArrayList<>();
    while (!ready.isEmpty()) {
        String node = ready.poll();
        order.add(node);
        for (String next : dependents.getOrDefault(node, List.of()))
            if (remaining.merge(next, -1, Integer::sum) == 0) ready.add(next);
    }
    if (order.size() != remaining.size()) throw new IllegalStateException("cycle among: " + remaining.keySet().stream().filter(n -> !order.contains(n)).toList());
    return order;
}

Every node starts with its in-degree; the ones at zero are ready; placing one decrements its dependents, and a dependent that reaches zero becomes ready. O(V + E), and the cycle check is free: if the order comes out shorter than the node count, whatever is left is in a cycle, and the message can name it — which is exactly what Spring's BeanCurrentlyInCreationException and Maven's "cyclic reference" do.

The second algorithm is DFS with post-order: run DFS from every unvisited node, append each node to the result after all its descendants have been finished, then reverse. It is shorter to write and detects a cycle by meeting a node that is on the current path (grey, not yet black), which is the three-colour marking from the section above. Kahn's is the one that also gives you which nodes are ready at once — the parallel build's level of independent modules — and the one where a priority queue instead of a deque yields the lexicographically smallest order when several are valid.

Choosing

The questionUse
fewest hops from A to BBFS
cheapest route, weighted edgesDijkstra — BFS with a priority queue
is there any path from A to Beither; DFS is usually less code
all vertices reachable from Aeither
does this graph have a cycleDFS
a valid build orderDFS, topological sort
the whole graph is huge and the answer is probably nearBFS
the whole graph is huge and the answer is probably deepDFS

The last two rows are the practical ones. BFS holds an entire frontier in memory, which for a wide graph can be enormous. DFS holds one path, which is cheap — and can wander very deep down a branch that has no answer.

Under the hood: why ArrayDeque for both, and what recursive DFS actually spends

Both loops in this lesson reach for ArrayDeque — not LinkedList, which is the textbook-familiar Deque implementation — and the collections lesson's measurement is why: ArrayDeque's circular-array push/pop/poll are one array write and an index update each, with no node allocation, where LinkedList would allocate a node object per element. For a BFS or DFS that can touch millions of vertices, that difference is not cosmetic; it is the gap the which-structure lesson measured as LinkedList losing to ArrayList-family structures by three orders of magnitude on operations it is supposedly built for.

Recursive DFS's real cost is the one this course keeps returning to: a stack frame per call, on the actual JVM call stack, not on a heap-allocated Deque. The iterative version in this lesson's code trades that for an explicit Deque<Node> living on the heap — which has no fixed ceiling beyond available memory, unlike the JVM's per-thread stack. That is precisely why "recursive DFS on a graph a hundred thousand deep overflows, and the iterative version does not": it is not that the iterative version does less work, it is that it spends a resource (heap) with a much higher ceiling than the resource (call-stack depth) the recursive version spends, for the identical O(V+E) work either way.

One more mechanical detail worth being precise about: iterative DFS with a stack does not, in general, visit nodes in the exact same order as the recursive version. Recursive DFS fully finishes exploring one neighbour (and everything reachable from it) before moving to the next; the iterative version pushes all of a node's neighbours before popping the next one, so if a node has multiple neighbours, the iterative walk can interleave differently depending on push order. For "is there a path" or "does a cycle exist" the difference never matters — both still visit every reachable node exactly once — but it does matter for anything that depends on the specific traversal order, like recording a specific valid topological sequence.

Try it yourself

Trace the order a stack produces

java
Map<String, List<String>> graph = new LinkedHashMap<>();
graph.put("a", List.of("b", "c"));
graph.put("b", List.of());
graph.put("c", List.of("d", "e"));
graph.put("d", List.of());
graph.put("e", List.of());
 
Deque<String> stack = new ArrayDeque<>();
Set<String> seen = new HashSet<>();
List<String> order = new ArrayList<>();
stack.push("a");
seen.add("a");
while (!stack.isEmpty()) {
    String v = stack.pop();
    order.add(v);
    for (String n : graph.get(v)) if (seen.add(n)) stack.push(n);
}
System.out.println(order);

Before running it: a's neighbours are pushed in the order b, then c — so c sits on top of the stack. Which gets visited next, b or c?

Why the last neighbour pushed is the first one visited

A stack is last-in-first-out, so pushing b then c means c pops first — the traversal visits a, then c (not b, even though b was a's first-listed neighbour), then dives into c's neighbours d and e before ever returning to b. This is the concrete version of "DFS commits to a path": the order a stack-based DFS actually explores depends on the order neighbours are pushed, which is the reverse of the order they are listed — a detail that matters whenever a problem's answer depends on which valid path DFS finds, not merely whether one exists.

Misconceptions

  • "Iterative DFS with a stack visits nodes in the same order as recursive DFS." Not necessarily — the exercise above shows a stack visiting c before b even though b is listed first, because pushing all neighbours before popping the next one interleaves differently than fully recursing into each neighbour in turn. Both still visit every reachable node exactly once; only the order can differ.
  • "BFS and DFS differ in what they can find, not just the order." For "is every vertex reachable", "does a cycle exist", or "are these two vertices connected", either traversal gives the same yes/no answer — the container only changes the order of discovery and, for BFS specifically, the guarantee that the first discovery is via a shortest unweighted path.

Sources

  • Thomas H. Cormen et al., Introduction to Algorithms (CLRS) — BFS, DFS, and topological sort by DFS finishing order.
  • Robert Sedgewick and Kevin Wayne, Algorithms (4th ed.) — graph traversal, and Kahn's algorithm for topological sort.
  • OpenJDK java.util.ArrayDeque class-level documentation — its stated complexity guarantees as both a stack and a queue.
Progress is saved on this device and to your account when signed in.