M24 · BFS and DFS

BFS and DFS on Graphs: Queues, Recursion and What Each Finds

Both searches start at one node and reach everything reachable from it, each node once. The only real difference is the waiting line: a FIFO queue makes BFS spread out in rings of equal distance, while the call stack makes DFS run down one path as far as it goes and back up. That single choice decides what each one is good at.

~50 minIntermediateC# · Python · Java · C++
Curriculum: M24 BFS and DFS · 1 of 1 lessons available

You will be able to

  • Run BFS and DFS by hand on a small directed or undirected graph, with neighbours in a fixed order, and predict the visit, discovery and finish orders.
  • Explain why BFS marks a node when it is enqueued, and why that makes its distances shortest paths in edges.
  • Use DFS colours (white, gray, black) to tell tree edges from back edges and detect a cycle in a directed graph.
  • Derive O(V + E) time and O(V) extra space for both, and say where the E term comes from.
  • Choose between BFS and DFS for shortest paths, components, cycle detection, flood fill and ordering problems.

Helpful before this lesson

  • M23 Graph Fundamentals — Graph vocabulary and representations, and how density changes the right choice.
  • M09 Queues and Deques — First in, first out, ring buffers, double-ended queues and the monotonic deque.
  • M11 Recursion — Base cases, the call stack, recursion trees and the first look at memoization.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A graph search answers "what can I reach from here, and how?" It keeps three kinds of nodes:

  • undiscovered (white): not seen yet;
  • discovered (gray): seen, but its edges have not all been followed;
  • done (black): every edge out of it has been examined.

Each step takes one gray node and looks along its edges for white ones. What differs is which gray node goes next:

  • Breadth-first search (BFS) takes the one that has waited longest: a FIFO queue. The start node's neighbours are handled before their neighbours, so the search spreads in rings: everything at distance 1, then everything at distance 2, and so on.
  • Depth-first search (DFS) takes the one seen most recently: a stack, here the call stack of a recursive function. It follows one path as deep as possible, then backs up to the last node that still has an unexplored edge.

The lab draws the graph on a circle (so no edge passes behind another node), the queue or call stack as a row in front of it, and the visit order below that. Switch between the presets BFS: levels and DFS: deep first: same graph, same start, very different orders.

Both searches are deterministic only if the neighbour order is. Everything in this lesson, the lab and the four implementations takes neighbours in ascending order (adjacency lists are sorted). With another order you get another valid BFS or DFS, so do not compare your hand trace with a library's output unless you know its order.

bfs(adj, start):
    dist = [-1] * n;  dist[start] = 0
    queue = [start]
    while queue not empty:
        u = queue.dequeue()                 # visit u
        for v in adj[u]:                    # ascending
            if dist[v] != -1: continue      # already discovered
            dist[v] = dist[u] + 1           # discover v
            queue.enqueue(v)

Mark on enqueue, not on dequeue. dist[v] doubles as the visited flag and is set the moment v is discovered. If you only marked nodes when they leave the queue, a node with several discovered neighbours could be enqueued several times: wasted work, and in dense graphs up to E queue entries instead of V.

Why the distances are shortest paths. The queue always holds nodes of at most two consecutive distances, d followed by d + 1, in that order. Nodes therefore leave the queue in nondecreasing distance, so the first time any node is discovered, it is discovered from a node as close to the start as possible. That first discovery fixes dist[v], and it is never improved later. This holds for unweighted graphs (every edge costs 1). With weights you need Dijkstra's algorithm (module M26), which replaces the queue with a priority queue.

Store parent[v] = u at discovery and you can rebuild a shortest path to any node by following parents back to the start. The lab's Nodes panel shows that parent column; the green edges are the BFS tree it defines.

dfs(u):
    visited[u] = true; discovery.append(u)   # u turns gray
    for v in adj[u]:                         # ascending
        if visited[v]: continue
        dfs(v)                               # tree edge u → v
    finish.append(u)                         # u turns black

DFS produces two orders. Discovery order (preorder) records when a call starts; finish order (postorder) records when it returns, after everything reachable through unvisited nodes has been explored. Finish order is what topological sorting by DFS and many graph algorithms build on.

The interesting moment is an edge u → v to a node that is not white:

v is… Directed graph Undirected graph
gray (still on the call stack) back edge: v is an ancestor of u, so v → … → u → v is a cycle if v is u's parent, it is the edge just used, not a cycle; otherwise a back edge and a cycle
black (finished) forward or cross edge: no cycle through it the edge was already explored from v's side

So a directed graph has a cycle exactly when DFS finds a back edge. The preset Directed DFS: a cycle reaches edge 4 → 1 while 1 is still gray and marks it in red. That is the cycle test behind DFS-based topological sort.

DFS can also be written with an explicit stack. A version that pushes all neighbours at once and marks nodes when popped visits nodes in a valid depth-first preorder, but not necessarily the same order as the recursion, and it does not give finish times. To reproduce the recursion exactly, keep (node, next-neighbour index) pairs on the stack. That is what the tests use as an independent reference.

Cost: O(V + E)

Both searches do two kinds of work:

  1. Per node: each reachable node is discovered once and visited once (dequeued or entered). That is O(V).
  2. Per adjacency entry: when a node is visited, its whole adjacency list is scanned once. Over the whole run that is the sum of all list lengths: E for a directed graph, 2E for an undirected one (each edge is listed at both ends).

Total: O(V + E) time. Extra space is O(V) for the visited/distance arrays plus the queue (at most V entries) or the recursion (at most V frames deep). The Adjacency checks metric in the lab counts exactly the second term; on the connected undirected Grid as a graph preset it equals twice the number of edges.

The bound assumes adjacency lists. With an adjacency matrix, scanning a node's neighbours means reading a whole row of V cells, so both searches become O(V²) no matter how few edges there are (see graph representations).

A single call only reaches the start node's component. Nodes 7 and 8 in the BFS: levels preset stay white. To visit every node, loop over all nodes and start a new search from each one still white. Every new start is a new connected component (undirected) and the total is still O(V + E).

Which one when

Task Use Why
Fewest edges from a source (unweighted) BFS rings of equal distance; first discovery is shortest
Shortest path on a grid with 4-neighbour moves BFS a grid is an unweighted graph
Distance to the nearest of several sources multi-source BFS enqueue every source at distance 0
Connected components, flood fill, reachability either both visit exactly the reachable set
Cycle detection in a directed graph DFS back edge to a gray node
Topological order, strongly connected components DFS (finish order) or Kahn's algorithm ordering falls out of finish times
Two-colouring (is the graph bipartite?) BFS or DFS colour by level parity; a same-colour edge means odd cycle
Very deep or long-path graphs BFS or iterative DFS recursion depth = longest DFS path

Grids are graphs

A grid of R × C cells is a graph with a node per cell and an edge between orthogonal neighbours; you rarely build it explicitly. Number cell (r, c) as r * C + c, and generate neighbours on the fly with bounds checks (and walls skipped). The Grid as a graph preset is a 3 × 3 grid built that way: BFS from the corner discovers cells in diagonal waves, and the distance tag of each cell is r + c, its Manhattan distance.

Language notes

  • C#: Queue<int> for BFS; recursion for DFS. A default thread stack (1 MB on Windows) holds tens of thousands of small frames, not millions; use Stack<T> with (node, index) pairs for huge graphs.
  • Python: use collections.deque with popleft(), never list.pop(0), which shifts the whole list and turns BFS quadratic. Recursive DFS hits the default recursion limit (1,000) on long paths; sys.setrecursionlimit only moves the problem, so prefer an explicit stack there.
  • Java: ArrayDeque<Integer> as the queue (add/remove); avoid the legacy Stack class. Deep recursion throws StackOverflowError; the thread stack size can be raised, but an iterative version is more robust.
  • C++: std::queue<int> (a deque underneath). The visited flags use std::vector<bool>, a space-optimised bitset specialisation: compact, but its elements are proxies rather than real bool& references.

The teaching implementation

Adjacency builds sorted lists from an edge list; Bfs returns the visit order and distances (−1 for unreachable); Dfs returns discovery and finish orders. The four languages share the same structure line by line. Each is tested against one shared fixture of exact orders (directed and undirected graphs, cycles, unreachable nodes, a grid, a single node, edges given in scrambled order) and against 500 random graphs: BFS distances are compared with a simple Bellman–Ford relaxation, and DFS orders with an explicit-stack DFS.

Common mistakes

  • Marking visited on dequeue in BFS: duplicates in the queue, and in some variants wrong distances.
  • Forgetting the visited check in DFS on a graph with cycles: infinite recursion.
  • Treating the parent edge as a cycle in an undirected graph.
  • Using BFS distances on weighted graphs. BFS minimises the number of edges, not their total weight.
  • Assuming one call visits everything. It reaches one component; loop over all start nodes for the whole graph.
  • Relying on an unspecified neighbour order in tests or explanations.

Edge cases

  • Start node with no edges: BFS and DFS visit only the start. Try 3 nodes, the single edge 0 1 and start node 2.
  • Directed edges point one way: from a sink, nothing else is reachable even if every other node can reach it (Directed BFS preset).
  • Edges u → v and v → u in a directed graph are two different edges; the lab draws them side by side. In an undirected graph they would be one edge listed twice, which the input rejects.
  • Self-loops and duplicate edges are rejected by the lab to keep graphs simple; the algorithms themselves would just skip them as already discovered.

Worked practice

1. Undirected graph with edges 0–1, 0–2, 1–3, 2–3, 3–4. Give the BFS order and distances from 0, and the DFS discovery and finish orders.

Answer

Adjacency: 0: 1 2; 1: 0 3; 2: 0 3; 3: 1 2 4; 4: 3. BFS order 0 1 2 3 4 with distances 0, 1, 1, 2, 3. DFS: enter 0, 1, 3, 2 (edge 2–0 is a back edge: cycle 0–1–3–2), finish 2, enter 4, finish 4, 3, 1, 0. Discovery 0 1 3 2 4; finish 2 4 3 1 0.

2. Why can the BFS queue never contain a node at distance d + 2 while a node at distance d is still waiting?

Answer

A node w at distance d + 2 is enqueued while a node x at distance d + 1 is being visited. x itself was discovered from some distance-d node y. By the same argument one level down, every distance-d node was already in the queue before y left it, so all of them were enqueued before x. The queue is FIFO, so by the time x is dequeued (and w enqueued) every distance-d node has left.

3. Directed graph with edges 0 → 1, 1 → 2, 0 → 2. DFS from 0 sees edge 0 → 2 when 2 is already black. Is there a cycle?

Answer

No. 2 was finished during the call on 1, so 0 → 2 is a forward edge. Only an edge to a gray node (still on the stack) proves a cycle.

4. A maze is a 1,000 × 1,000 grid. Which search finds the shortest route from the entrance to the exit, and what does it cost?

Answer

BFS, because every move costs one step. V = 10⁶ cells and E ≤ 2 × 10⁶ edges, so O(V + E) is a few million operations. A recursive DFS would find a route but not necessarily the shortest, and its recursion could reach a million frames deep.

Summary

  • BFS uses a FIFO queue and visits nodes in rings of increasing distance; mark nodes when enqueued. Its distances are shortest paths in edges.
  • DFS uses recursion (a stack), producing discovery and finish orders; an edge to a gray node is a back edge, and in a directed graph that means a cycle.
  • Both run in O(V + E) time with adjacency lists and O(V) extra space; with a matrix they are O(V²).
  • One call covers one component; restart from unvisited nodes to cover the graph.
  • Fix the neighbour order if you need reproducible traces.

Full implementation

BFS and DFS in four languages, each checked against one shared fixture of exact visit, distance, discovery and finish orders (directed and undirected, cycles, unreachable nodes, a grid, a single node) and 500 random graphs compared with Bellman-Ford distances and an explicit-stack DFS.

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>
/// Breadth-first and depth-first search on adjacency lists. Nodes are 0..n-1 and
/// every list is sorted ascending, so neighbours are always taken in increasing
/// order. Both run in O(V + E) time and O(V) extra space.
/// </summary>
public static class GraphTraversal
{
    /// <summary>Adjacency lists, neighbours ascending; an undirected edge goes into both lists.</summary>
    public static List<int>[] Adjacency(int nodeCount, IEnumerable<(int From, int To)> edges, bool directed)
    {
        var adj = new List<int>[nodeCount];
        for (int i = 0; i < nodeCount; i++)
            adj[i] = [];
        foreach (var (u, v) in edges)
        {
            adj[u].Add(v);
            if (!directed)
                adj[v].Add(u);
        }
        foreach (var list in adj)
            list.Sort();
        return adj;
    }
 
    /// <summary>Visit order and distance in edges from start (-1 = unreachable).</summary>
    public static (List<int> Order, int[] Distance) Bfs(List<int>[] adj, int start)
    {
        var order = new List<int>();
        var dist = new int[adj.Length];
        Array.Fill(dist, -1);
        dist[start] = 0;
        var queue = new Queue<int>();
        queue.Enqueue(start);
        while (queue.Count > 0)
        {
            int u = queue.Dequeue();
            order.Add(u);
            foreach (int v in adj[u])
            {
                if (dist[v] != -1)
                    continue; // already discovered
                dist[v] = dist[u] + 1;
                queue.Enqueue(v);
            }
        }
        return (order, dist);
    }
 
    /// <summary>Discovery (preorder) and finish (postorder) order of a recursive DFS from start.</summary>
    public static (List<int> Discovery, List<int> Finish) Dfs(List<int>[] adj, int start)
    {
        var visited = new bool[adj.Length];
        var discovery = new List<int>();
        var finish = new List<int>();
        Visit(adj, start, visited, discovery, finish);
        return (discovery, finish);
    }
 
    private static void Visit(List<int>[] adj, int u, bool[] visited, List<int> discovery, List<int> finish)
    {
        visited[u] = true;
        discovery.Add(u);
        foreach (int v in adj[u])
        {
            if (visited[v])
                continue;
            Visit(adj, v, visited, discovery, finish);
        }
        finish.Add(u);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/GraphTraversal.cs

"""Breadth-first and depth-first search on adjacency lists.
 
Nodes are 0..n-1 and every list is sorted ascending, so neighbours are always
taken in increasing order. Both run in O(V + E) time and O(V) extra space.
"""
 
from __future__ import annotations
 
from collections import deque
from collections.abc import Iterable
 
 
def adjacency(node_count: int, edges: Iterable[tuple[int, int]], directed: bool) -> list[list[int]]:
    """Adjacency lists, neighbours ascending; an undirected edge goes into both lists."""
    adj: list[list[int]] = [[] for _ in range(node_count)]
    for u, v in edges:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)
    for neighbours in adj:
        neighbours.sort()
    return adj
 
 
def bfs(adj: list[list[int]], start: int) -> tuple[list[int], list[int]]:
    """Visit order and distance in edges from start (-1 = unreachable)."""
    order: list[int] = []
    dist = [-1] * len(adj)
    dist[start] = 0
    queue = deque([start])
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in adj[u]:
            if dist[v] != -1:
                continue  # already discovered
            dist[v] = dist[u] + 1
            queue.append(v)
    return order, dist
 
 
def dfs(adj: list[list[int]], start: int) -> tuple[list[int], list[int]]:
    """Discovery (preorder) and finish (postorder) order of a recursive DFS from start."""
    visited = [False] * len(adj)
    discovery: list[int] = []
    finish: list[int] = []
 
    def visit(u: int) -> None:
        visited[u] = True
        discovery.append(u)
        for v in adj[u]:
            if visited[v]:
                continue
            visit(v)
        finish.append(u)
 
    visit(start)
    return discovery, finish

Tested on CPython 3.14.0 · examples/python/dsa_examples/graph_traversal.py

package dev.bekadan.dsa.graphs;
 
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
 
/**
 * Breadth-first and depth-first search on adjacency lists. Nodes are 0..n-1 and
 * every list is sorted ascending, so neighbours are always taken in increasing
 * order. Both run in O(V + E) time and O(V) extra space.
 */
public final class GraphTraversal {
    private GraphTraversal() {
    }
 
    /** Visit order and distance in edges from the start (-1 = unreachable). */
    public record BfsResult(List<Integer> order, int[] distance) {
    }
 
    /** Discovery (preorder) and finish (postorder) order. */
    public record DfsResult(List<Integer> discovery, List<Integer> finish) {
    }
 
    /** Adjacency lists, neighbours ascending; an undirected edge goes into both lists. Each edge is {u, v}. */
    public static List<List<Integer>> adjacency(int nodeCount, int[][] edges, boolean directed) {
        List<List<Integer>> adj = new ArrayList<>(nodeCount);
        for (int i = 0; i < nodeCount; i++) {
            adj.add(new ArrayList<>());
        }
        for (int[] e : edges) {
            adj.get(e[0]).add(e[1]);
            if (!directed) {
                adj.get(e[1]).add(e[0]);
            }
        }
        for (List<Integer> list : adj) {
            Collections.sort(list);
        }
        return adj;
    }
 
    public static BfsResult bfs(List<List<Integer>> adj, int start) {
        List<Integer> order = new ArrayList<>();
        int[] dist = new int[adj.size()];
        Arrays.fill(dist, -1);
        dist[start] = 0;
        Queue<Integer> queue = new ArrayDeque<>();
        queue.add(start);
        while (!queue.isEmpty()) {
            int u = queue.remove();
            order.add(u);
            for (int v : adj.get(u)) {
                if (dist[v] != -1) {
                    continue; // already discovered
                }
                dist[v] = dist[u] + 1;
                queue.add(v);
            }
        }
        return new BfsResult(order, dist);
    }
 
    /** Recursive DFS from start. */
    public static DfsResult dfs(List<List<Integer>> adj, int start) {
        boolean[] visited = new boolean[adj.size()];
        List<Integer> discovery = new ArrayList<>();
        List<Integer> finish = new ArrayList<>();
        visit(adj, start, visited, discovery, finish);
        return new DfsResult(discovery, finish);
    }
 
    private static void visit(List<List<Integer>> adj, int u, boolean[] visited, List<Integer> discovery, List<Integer> finish) {
        visited[u] = true;
        discovery.add(u);
        for (int v : adj.get(u)) {
            if (visited[v]) {
                continue;
            }
            visit(adj, v, visited, discovery, finish);
        }
        finish.add(u);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/GraphTraversal.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <queue>
#include <utility>
#include <vector>
 
// Breadth-first and depth-first search on adjacency lists. Nodes are 0..n-1 and
// every list is sorted ascending, so neighbours are always taken in increasing
// order. Both run in O(V + E) time and O(V) extra space.
namespace bekadan::dsa::traversal {
 
using Adjacency = std::vector<std::vector<int>>;
 
// Adjacency lists, neighbours ascending; an undirected edge goes into both lists.
inline Adjacency adjacency(int node_count, const std::vector<std::pair<int, int>>& edges, bool directed) {
    Adjacency adj(node_count);
    for (const auto& [u, v] : edges) {
        adj[u].push_back(v);
        if (!directed) adj[v].push_back(u);
    }
    for (auto& list : adj) std::ranges::sort(list);
    return adj;
}
 
struct BfsResult {
    std::vector<int> order;
    std::vector<int> distance;  // -1 = unreachable
};
 
inline BfsResult bfs(const Adjacency& adj, int start) {
    std::vector<int> order;
    std::vector<int> dist(adj.size(), -1);
    dist[start] = 0;
    std::queue<int> queue;
    queue.push(start);
    while (!queue.empty()) {
        const int u = queue.front();
        queue.pop();
        order.push_back(u);
        for (const int v : adj[u]) {
            if (dist[v] != -1)
                continue;  // already discovered
            dist[v] = dist[u] + 1;
            queue.push(v);
        }
    }
    return {std::move(order), std::move(dist)};
}
 
struct DfsResult {
    std::vector<int> discovery;  // preorder
    std::vector<int> finish;     // postorder
    bool operator==(const DfsResult&) const = default;
};
 
namespace detail {
 
inline void visit(const Adjacency& adj, int u, std::vector<bool>& visited, DfsResult& out) {
    visited[u] = true;
    out.discovery.push_back(u);
    for (const int v : adj[u]) {
        if (visited[v])
            continue;
        visit(adj, v, visited, out);
    }
    out.finish.push_back(u);
}
 
}  // namespace detail
 
// Recursive DFS from start.
inline DfsResult dfs(const Adjacency& adj, int start) {
    std::vector<bool> visited(adj.size(), false);
    DfsResult out;
    detail::visit(adj, start, visited, out);
    return out;
}
 
}  // namespace bekadan::dsa::traversal

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/graph_traversal.hpp

References