Knowledge Guide
HomeDSAGraphs

Graph Traversal - Breadth First Search (BFS)

BFS explores a graph outward in concentric rings: it visits every vertex at distance k from the source before touching any vertex at distance k+1, by using a FIFO queue so vertices are processed in the exact order they were first discovered. This first-discovery order is what guarantees the ring-by-ring behaviour and makes BFS the algorithm of choice for shortest paths when every edge costs the same.

Recognize the pattern

Brute force → optimal

Brute force: to find the shortest-hop distance between two vertices you could enumerate all simple paths (DFS with backtracking) and take the minimum length — exponential, O(V!) in the worst case, because paths are re-explored with no memory of what's already the shortest way in.

Optimal (BFS): process vertices in strict order of discovery using a queue and a visited set. The first time a vertex is dequeued/enqueued, that distance is already minimal — no vertex is ever revisited with a shorter distance later, so each vertex and edge is examined a constant number of times. This turns exponential path enumeration into a single linear pass, O(V + E).

Complexity, derived

Time: each vertex is enqueued exactly once (guarded by the visited check) and dequeued exactly once → O(V) queue operations. When a vertex is dequeued, its full adjacency list is scanned once; summed over all vertices this touches each directed edge exactly once (each undirected edge twice) → O(E). Total: O(V + E).

Space: the visited array is O(V). The queue holds at most one full "frontier" (level) of vertices — in the worst case (e.g., a star graph) that frontier is O(V). Total: O(V) auxiliary space, plus O(V+E) for the adjacency-list representation itself.

Worked example

Graph: vertices {0,1,2,3,4}, edges (0,1),(0,2),(0,3),(1,2),(2,4). Start = 0.

StepDequeueQueue afterNewly discovered
10[1,2,3]1, 2, 3
21[2,3](0,2 already visited)
32[3,4]4
43[4]
54[]

Visit order: 0, 1, 2, 3, 4 — grouped exactly by distance from 0: {0} at distance 0, {1,2,3} at distance 1, {4} at distance 2.

Java implementation

import java.util.*;

class BFS {
    // adj: adjacency list, n vertices, returns visit order from start
    static List<Integer> bfs(List<List<Integer>> adj, int n, int start) {
        boolean[] visited = new boolean[n];
        int[] dist = new int[n];
        Arrays.fill(dist, -1);
        Queue<Integer> queue = new ArrayDeque<>();
        List<Integer> order = new ArrayList<>();

        visited[start] = true;
        dist[start] = 0;
        queue.add(start);

        while (!queue.isEmpty()) {
            int current = queue.poll();
            order.add(current);
            for (int neighbor : adj.get(current)) {
                if (!visited[neighbor]) {
                    visited[neighbor] = true;
                    dist[neighbor] = dist[current] + 1;
                    queue.add(neighbor);
                }
            }
        }
        return order;
    }
}

Key detail: mark visited[neighbor] = true at enqueue time, not at dequeue time — otherwise the same neighbor can be pushed onto the queue multiple times by different frontier vertices before it is ever processed, wasting time and space (and breaking the O(V+E) bound).

Pitfalls

When to use / when not — trade-offs

Use BFS when you need shortest path / minimum steps in an unweighted graph, level-order processing, or to find connected components/bipartiteness.

Prefer DFS instead when you only need reachability, topological order, cycle detection, or path enumeration/backtracking — DFS uses O(depth) stack space versus BFS's O(width-of-frontier) queue space, which matters on wide shallow graphs where BFS's memory footprint can dwarf DFS's.

Prefer Dijkstra instead of BFS when edges carry positive weights — Dijkstra generalizes BFS's frontier idea using a priority queue keyed by accumulated distance, at O((V+E) log V) instead of O(V+E).

Takeaways

Recall: Why must a vertex be marked visited when it is enqueued rather than when it is dequeued?


Synthesized from graph traversal fundamentals (CLRS-style BFS analysis) and standard interview-prep BFS references.

🤖 Don't fully get this? Learn it with Claude

Stuck on Graph Traversal - Breadth First Search (BFS)? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Graph Traversal - Breadth First Search (BFS)** (DSA) and want to truly understand it. Explain Graph Traversal - Breadth First Search (BFS) from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Graph Traversal - Breadth First Search (BFS)** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Graph Traversal - Breadth First Search (BFS)** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Graph Traversal - Breadth First Search (BFS)** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes