Breadth-first search: Examples & Code

Algorithm Visualizations November 16, 2026 javascript

Published by Dimitris Kougioumtzis · Updated

Visit nodes in queue order, exploring one level at a time.

A queue explores one edge-distance layer at a time; marking on enqueue prevents duplicate frontier entries.

Open the 3D visualization

Breadth-first search example state preview
Preview of the example's final state. Complete values are available in the worked example and interactive timeline.

When to use Breadth-first search

Reachability and minimum-hop routes.

Choosing an alternative

Dijkstra accounts for edge costs; DFS does not generally find shortest paths.

Worked example: input and state changes

Example input

0,1,4; 0,2,2; 2,1,1; 1,3,5; 2,3,8; 3,4,2

These checkpoints follow the actual example timeline. State details show the stored values and decisions; use the visualization to inspect every intervening step.

  1. Step 0: Initial graph.

    State at this checkpoint
    {
      "values": [
        "∞",
        "∞",
        "∞",
        "∞",
        "∞"
      ],
      "active": [],
      "kind": "graph",
      "visited": [],
      "chosen": []
    }
  2. Step 3: Enqueue node 2; queue: 1, 2.

    State at this checkpoint
    {
      "values": [
        1,
        "∞",
        "∞",
        "∞",
        "∞"
      ],
      "active": [
        2
      ],
      "kind": "graph",
      "visited": [
        0
      ],
      "chosen": []
    }
  3. Step 5: Enqueue node 3; queue: 2, 3.

    State at this checkpoint
    {
      "values": [
        1,
        2,
        "∞",
        "∞",
        "∞"
      ],
      "active": [
        3
      ],
      "kind": "graph",
      "visited": [
        0,
        1
      ],
      "chosen": []
    }
  4. Step 8: Enqueue node 4; queue: 4.

    State at this checkpoint
    {
      "values": [
        1,
        2,
        3,
        4,
        "∞"
      ],
      "active": [
        4
      ],
      "kind": "graph",
      "visited": [
        0,
        1,
        2,
        3
      ],
      "chosen": []
    }
  5. Step 10: Traversal order: 0 → 1 → 2 → 3 → 4. Unreachable nodes stay unvisited.

    State at this checkpoint
    {
      "values": [
        1,
        2,
        3,
        4,
        5
      ],
      "active": [],
      "kind": "graph",
      "visited": [
        0,
        1,
        2,
        3,
        4
      ],
      "chosen": []
    }

Expected final state

Traversal order: 0 → 1 → 2 → 3 → 4. Unreachable nodes stay unvisited.

Complexity and input bounds

Family: Graphs. Time complexity: O(V + E).

Implementation detail: With adjacency lists BFS is O(V + E). The downloadable edge-array version scans all E edges per expanded vertex, giving O(V + VE).

Space complexity: O(V) queue and visited state.

Working-space bounds describe algorithm state and any explicitly noted output, excluding the visualization's saved timeline. Recording frames can use more memory than running the function alone. Here n is sequence length, V and E are vertex and edge counts, and other parameters refer to the named input dimensions.

Directed edges as source,target,weight; separated by semicolons. Nodes 0–7, positive weights 1–99. Start node is 0.

The playground validates these limits before starting. Downloaded functions are callable implementations, with parameter and output-buffer contracts in their comments; they do not all repeat the playground's input validation.

Common mistakes and limitations

Fewest edges is not minimum total weight, and disconnected vertices remain unvisited.

Further reading

For background on algorithm analysis and the JavaScript function interface:

Editorial and testing approach · Browse all algorithm guides

Complete JavaScript implementation

javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Directed edge arrays from, to, weight; nodes 0..vertices-1; source 0. Up to 8 vertices, 16 edges. Allocate output with at least 256 integers. Writes traversal order and returns its length. Reference snippets assume validated playground inputs. Fixed scratch buffers have 256 slots. Sorting variants may use a different traversal strategy than the animation.
function algorithm(from, to, weight, edges, vertices, output) {
    let seen = Array(256).fill(0); let queue = Array(256).fill(0);
    let head = 0; let tail = 0; let count = 0;
    queue[tail++] = 0; seen[0] = 1;
    while (head < tail) {
        let u = queue[head++]; output[count++] = u;
        for (let i = 0; i < edges; i++) {
            let v = to[i];
            if (from[i] == u && seen[v] == 0) { seen[v] = 1; queue[tail++] = v; }
        }
    }
    return count;
}

Source

An early breadth-first routing paper; BFS has several historical origins. The playground uses a general graph traversal.