Algorithm · Graphs · O(V + E)

BFS and DFS

Breadth-first search explores a graph in rings of increasing distance with a queue; depth-first search follows one path as far as it goes. Both run in O(V + E).

The full derivation, edge cases and exercises are in the lesson Graph representations: edge list, adjacency matrix and adjacency list. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Both searches mark vertices as visited so each is processed once. BFS uses a queue, so it reaches vertices in order of their edge distance from the start and finds shortest paths in unweighted graphs. DFS uses a stack (often the call stack) and records discovery and finish times, the basis for cycle detection and topological order.

Steps

  1. Mark the start vertex visited and put it in the frontier (queue for BFS, stack for DFS).
  2. Take a vertex from the frontier and look at its neighbours.
  3. Add every unvisited neighbour to the frontier and mark it.
  4. Repeat until the frontier is empty.

Invariants

What holds at every step; the correctness argument rests on these.

  • No vertex is added to the frontier twice.
  • BFS: vertices leave the queue in non-decreasing distance from the start.

Complexity

BFS and DFS complexity
CaseTimeExtra spaceNotes
Adjacency listsO(V + E)O(V)O(V²) with an adjacency matrix.

When to use it

Use it when

  • Reachability, connected components, shortest paths by edge count (BFS), cycle detection and ordering (DFS).

Avoid it when

  • Edges have different weights and you need shortest paths: use Dijkstra.

Step through it

The interactive lab for bfs and dfs: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Data structures it uses

Problems, patterns and exercises

References