Best on a larger screen — the animation and controls have more room to breathe.
Inputs

Breadth-First Search

Breadth-first search (BFS) is a graph traversal algorithm that visits nodes in order of increasing distance from a start node, using a FIFO queue to process the closest unvisited frontier first. Because the first arrival at any node travels a minimum number of edges, BFS computes shortest paths in unweighted graphs in O(V + E) time.

BFS expands outward like ripples from a stone dropped in a pond: every node at distance one is reached before any node at distance two, and distance two finishes before distance three. The FIFO queue enforces this order by appending newly discovered nodes at the back and dequeuing the next node from the front.

How Breadth-First Search Works

The algorithm is a single loop over a queue:

  1. Enqueue the start node, mark it visited, and set its distance to 0.
  2. While the queue is non-empty, dequeue the front node and scan its neighbours. Mark each unvisited neighbour, assign distance current + 1, and push it onto the back of the queue.

One detail in step 2 is required for correctness: mark a node visited as soon as you enqueue it, not when you dequeue it. Waiting until dequeue allows the same node to be discovered by multiple neighbours and pushed several times, causing duplicated work and corrupted distances. In the animated graph-mode code, visited.add(nb) sits directly beside append inside the if nb not in visited block for this reason.

This lesson runs in two modes. In Tree mode, there is one path to every node, so reconvergence cannot occur; the animated tree code omits the visited set, leaving a short loop that dequeues a node, records each child's distance, and pushes its children. In Graph mode, edges may reconverge or form cycles, so the visited set guards every enqueue. Any edge pointing to an already-discovered node is skipped because that node already has a distance from an earlier (equal-or-shorter) path. A skipped edge is a back edge if its target is an ancestor of the current node in the BFS tree, and a cross edge otherwise.

Because nodes leave the queue in non-decreasing distance order, the first edge to reach a node determines its shortest distance. In an unweighted graph, BFS finds shortest paths directly.

Breadth-First Search Step by Step

The default configuration is Graph mode, Simple preset, starting at node 0: a 7-node graph where two paths converge on node 5 (0 → [1, 2], 1 → [3, 4], 2 → [5], 4 → [5], 5 → [6], with 3 and 6 as leaves). This reconvergence shows how the visited set turns a second arrival into a skipped cross edge instead of duplicated work.

  1. Enqueue 0. Mark it visited with d = 0. Queue: [0].
  2. Dequeue 0. Both 0 → 1 and 0 → 2 are unvisited, so enqueue each at d = 1. Queue: [1, 2], completing level 1 before any level-2 node is discovered.
  3. Dequeue 1. Enqueue 1 → 3 and 1 → 4 at d = 2. Queue: [2, 3, 4].
  4. Dequeue 2. Edge 2 → 5 reaches an unvisited node, so enqueue 5 at d = 2. Because this is 5's first arrival, 2 is its parent and d(5) = 2 is final. Queue: [3, 4, 5].
  5. Dequeue 3. Node 3 is a leaf, so nothing is pushed. Queue: [4, 5].
  6. Dequeue 4. Scanning 4 → 5 finds that 5 is already discovered. Edge 4 → 5 is a cross edge and is skipped without enqueuing, because the path through 4 is no shorter than the path through 2. Queue: [5].
  7. Dequeue 5 and 6. Dequeuing 5 enqueues 5 → 6 at d = 3, leaving queue [6]. Dequeuing leaf 6 empties the queue.

Visit order: 0, 1, 2, 3, 4, 5, 6, with distances 0 / 1, 1 / 2, 2, 2 / 3. Although the order looks like plain level order, step 6 shows the difference between traversing a tree and traversing a graph: node 5 has two incoming paths, BFS takes the first, and the visited set skips the second as a cross edge. Without that guard, 4 → 5 would re-enqueue 5 with a corrupted distance.

The other presets isolate specific cases. Tree mode (Balanced) removes reconvergence so every node has one path and no cross edges appear, visiting 0, 1, 2, 3, 4, 5, 6 in level order on the complete binary tree (compared with depth-first search's 0, 1, 3, 4, 2, 5, 6 on the same shape). The graph Cyclic preset highlights cycle protection: every cycle-closing edge hits an already-discovered node and is skipped, preventing an infinite queue. From node 0, 2 → 0 points back to 2's ancestor (a back edge), while 2 → 4, 4 → 5, and 5 → 1 are cross edges. Use those presets to examine queue mechanics or cycle handling separately; the default shows both together.

On the canvas, the queue appears as the bottom strip: chips enter at the back on enqueue and leave from the front on dequeue, while a focus ring marks the node just popped. Node color encodes state: faint blue for unreached, orange for discovered and waiting in the queue, and green for fully scanned. Each discovered node displays its d= label as the orange frontier advances one distance ring at a time, and any skipped back or cross edge flashes red.

Time and Space Complexity

CaseTimeSpace
AllO(V + E)O(V)

Each vertex is enqueued and dequeued once (guaranteed by marking on enqueue), and each edge is examined once. Space covers the queue and the visited set. At any point, the queue holds at most two adjacent levels: the remainder of the current level plus the portion of the next level discovered so far. Its peak size therefore tracks the graph's width. On a wide, bushy graph the queue can hold a large fraction of all vertices at once, whereas DFS's stack stays shallow; the visited set costs O(V) in both.

Edge Cases

  • Single node, no edges: enqueue the start node, dequeue it, find no neighbours, and terminate.
  • Unreachable nodes: BFS visits only nodes reachable from the start along directed edges (or the start's connected component in an undirected graph); remaining nodes stay unvisited. Covering the entire graph requires restarting from each unvisited node.
  • Cycles: every cycle-closing edge hits a discovered node and is skipped (as a back edge if its target is an ancestor, or a cross edge otherwise), so the queue cannot grow without bound.
  • Wide versus deep input: a broad frontier fills the queue, whereas a long chain keeps it small. This is the opposite of DFS's stack behavior.

Common Mistakes

  1. Marking visited on dequeue instead of enqueue. The same node gets pushed by multiple neighbours before it is processed, causing extra work and wrong distances. Mark each node as soon as it enters the queue.
  2. Using BFS on a weighted graph. BFS counts edges, so shortest-path optimality holds only when every edge has equal weight. Varying weights require Dijkstra's algorithm.
  3. Swapping the queue for a stack unintentionally. Replacing FIFO with LIFO turns BFS into DFS because the container determines traversal order. If a traversal dives deep instead of expanding level by level, check which end pop removes from in your language's library.
  4. Dropping the visited set in graph mode. Any cycle then re-enqueues the same nodes endlessly. Only a tree without cycles can omit the visited set.