# bfs

> explore a graph level by level with a queue.

source: https://learning.anthnydas.com/algos/bfs/

## tl;dr

a queue of vertices to look at. the front one comes out, and every neighbor it reaches for the first time goes on the back with a distance one more than its own. the source comes out first, then everything one edge away, then two, so the first time a vertex is reached is along a shortest path.

- **time:** O(n + m) (every reached vertex out of the queue once, every edge looked at from each end)
- **shortest paths:** by edge count (a distance and a parent per vertex, from one source)
- **space:** O(n) (a queue of n slots, dist and parent)
- **weights:** ignored (it counts edges. for weights, dijkstra)
- **all pairs:** n runs (one source per run)
- **reach for it:** the shortest way through a maze or across a grid, by moves, the fewest hops, like links between pages, degrees of separation or word ladders, what one vertex can reach, and its connected component, the levels of a tree, top to bottom, the flood fill behind rotting oranges and the paint bucket, the step before dijkstra and a*

breadth-first search walks a graph outward from one vertex, a level at a time: the source, then everything one edge away, then two, and so on. a queue keeps the order. the vertex at the front comes out, and every neighbor it reaches for the first time goes on the back, with a distance one more than its own. that's the whole algorithm, and it comes with a guarantee: the first time bfs reaches a vertex is along a shortest path, counted in edges. it finds the way through a maze, the fewest hops between two pages, and how far everything is from one place, in one pass over the graph.

## the idea

> **interactive figure:** an animation in six steps on the graph from the graphs page: 6 vertices, 0 to 5, with 7 edges, drawn by level from 0: 0 on top, 1 and 2 under it, 3 and 4 under them, and 5 at the bottom. a vertex shows its distance as a mark the moment it gets one. with the graph go two rows of chips: the queue, front on the left, and the vertices that came out, in order. the vertex that just came out has a thick white ring, the ones that came out before it are filled white, and the ones waiting in the queue have a dashed ring. first 0 is cyan, with the mark 0, and its chip is the only one in the queue. then 0 comes out and its chip moves down to the out row: the edge to 1 turns white, 1 gets the mark 1 and a chip at the back of the queue, then the same for 2, and both edges stay cyan as parent edges. then 1 comes out: the look back at 0 is a dashed line, the look at 2 finds it reached and that edge dims, and 3 gets the mark 2. 2 comes out and 4 gets 2, so the queue holds 3 and 4. then 3 comes out and 5 gets 3, and 4 comes out and finds 5 waiting already, so the edge from 4 to 5 dims. last, 5 comes out with nothing new, the queue is empty, and the path to 5 lights up in white from 5 back through its parents, 3, 1 and 0. the last step turns the path cyan again, leaving the tree of parent edges, and brackets under the out row group the six by level: 0, then 1 and 2, then 3 and 4, then 5.

the graph from the graphs page: 6 vertices, 7 edges. bfs starts at 0. its distance is 0, and it's the only vertex in the queue. every other vertex is unreached: no distance yet.

0 comes out of the front of the queue. it has two neighbors, 1 and 2, and neither has a distance: each gets 1, remembers 0 as its parent, and goes on the back of the queue. the queue is now the whole of level 1.

1 comes out. 0 and 2 have distances already, so nothing happens to them. 3 is new: distance 2, parent 1, into the queue. then 2 comes out and finds 4: distance 2, parent 2. level 1 is done, and the queue holds level 2.

3 comes out and reaches 5: distance 3. then 4 comes out and looks at 5 too, but 5 is in the queue already, put there by 3. that's the tie rule: whichever vertex comes out of the queue first claims the neighbor.

5 comes out with nothing new to find, and the queue is empty: 6 vertices came out, and 14 looks at a neighbor, two per edge. the path to 5 follows the parents back: 5 came from 3, 3 from 1, 1 from 0. three edges, and no path is shorter.

by level: 0, then 1 and 2, then 3 and 4, then 5. the queue only ever held one level and the start of the next. that's why the first time bfs reaches a vertex is along a shortest path.

## watch it run

a maze is where bfs started: moore's 1959 paper was about the shortest path through a maze, and lee's 1961 wire-routing algorithm floods a grid the same way.[^history] here every open cell is a vertex, and its open neighbors, up, left, right and down, are its edges. the cell that just came out of the queue is white, cells waiting in the queue have a ring, and a cell shows its distance from the start the moment it gets one, with an arrow toward the cell it came from. a short white line is a look at a neighbor. tap a cell to turn it into a wall, or a wall back into a cell. the pseudocode follows along.

> **interactive figure:** an interactive stepper over a maze of 7 columns and 5 rows: the start at row 2, column 0 in cyan, the goal at row 2, column 6 in amber, and 8 walls, two columns of four at columns 3 and 5, rows 0 to 3, which leave a gap along the bottom row. each step is one cell out of the queue, filled white, or one look at a neighbor, drawn as a short white line from the cell that came out. a new neighbor gets its distance, a ring and an arrow toward its parent, and joins the queue, drawn as chips under the maze, front first. a neighbor that was reached already is noted and skipped. cells that came out turn a quiet cyan. the matching pseudocode line is highlighted, with counts of the cells out of the queue, the looks at a neighbor, and the level. the flood is a diamond around the start in the block of 15 cells on the left, then it runs along the bottom row and up the two corridors: the dead end at column 4, which it fills to the top, and column 6, where it reaches the goal and keeps going to the two cells past it. the goal gets its distance, 10, when the cell below it comes out of the queue, the 23rd of 27, and comes out itself 25th: a straight line would be 6 steps, but the walls make it 10. at the end the path lights up through the parents: right two, down two, right four along the bottom, up two. 27 cells come out, 68 looks, 13 levels, and the queue never holds more than 5 cells. tap a cell to make it a wall, or a wall to open it, and the figure jumps to the end of the new run, with its distances and its path. a button puts the page's maze back.

watch the corridor at column 4: it's a dead end, and the flood fills it to the top anyway, a level at a time alongside the corridor to the goal, because bfs can't tell a dead end from a way through. and watch the ties: (4, 2) touches (3, 2) and (4, 1), both at level 3, and (3, 2) came out of the queue first, so it's the parent, and the path at the end comes down through it. put a wall on (3, 2) and the path comes down through (4, 1) instead, still 10 steps.

## try it

the queue is the whole trick. keep it in your head for one step.

> **interactive figure:** a practice exercise on small graphs of 5 to 8 vertices, drawn on a circle next to their adjacency lists, with the source in cyan. four kinds of question. a vertex has just come out of the queue: it has a thick white ring and its list is lit, the vertices that came out before it are filled white, the ones waiting are ringed, the distances found so far are marks with their parent edges in cyan, and the queue is a row of chips under the graph. what does the queue hold once its neighbors are looked at? the traps are every neighbor again, the new ones in front, and the new ones alone, and once you answer, the new neighbors take their distances and join the queue in white. some vertices have come out, listed in the question, and the queue is hidden, though what waits in it is ringed: which comes out next? how many edges does the shortest path from the source to the vertex in amber take, with no distances shown? once you answer, the path lights up. and which of a vertex's neighbors is its parent, the one that put it in the queue? the distances show, but not the parent edges, and the order the vertices came out is listed under the graph, since when two neighbors sit on the level above, the one that came out first wins. once you answer, the parent edge lights up. the first question is the page's graph right after 1 comes out: the queue holds 2, and the answer is 2, 3.

## pseudocode

```text
bfs(adj, src):  # adj[u] lists the neighbors of u, vertices 0 to n - 1
  dist = [-1] * n  # -1: not reached yet
  parent = [-1] * n
  queue = [0] * n; head = 0; tail = 0  # a vertex enters once, so n slots are enough
  dist[src] = 0
  queue[tail] = src; tail += 1
  while head < tail:  # something is waiting
    u = queue[head]; head += 1  # the front: the oldest vertex waiting
    for v in adj[u]:
      if dist[v] != -1: continue  # reached already, by a path no longer than this one
      dist[v] = dist[u] + 1  # one level past u
      parent[v] = u
      queue[tail] = v; tail += 1  # the back: v waits its turn
  return dist, parent

path_to(dist, parent, v):
  if dist[v] == -1: return []  # never reached
  path = []
  while v != -1:  # src's parent is -1
    path.append(v); v = parent[v]
  return reversed(path)  # src first
```

the queue is an array of n slots with two indexes: `head` is the front, where vertices come out, and `tail` is the back, where they go in. a vertex gets its distance when it enters the queue, so it enters once, n slots are enough, and nothing ever shifts. `dist` doubles as the seen mark: -1 means unreached. `path_to` walks the parents back from v and reverses, so the source comes first.

## the queue, up close

> **interactive figure:** a table of the queue on the page's graph after each of the six pops, one row per pop: the vertex that came out, filled white, then the chips left in the queue once its neighbors were looked at, front first, with the level coming out in cyan and the level after it in amber, then the levels in the queue. after 0: 1 and 2, both level 1. after 1: 2 on level 1, then 3 on level 2. after 2: 3 and 4, both level 2. after 3: 4 on level 2, then 5 on level 3. after 4: 5, level 3. after 5: empty. no row holds three levels, and a lower level never sits behind a higher one.

- **two levels, in order.** the queue holds vertices at level d, then vertices at level d + 1, and nothing else. when a level-d vertex comes out, everything it adds is level d + 1 and goes behind what's already there. the first level-(d + 1) vertex comes out only when every level-d vertex has, so the levels come out in order: 0, then every 1, then every 2. the 27 cells of the maze come out in distance order, and over 300 seeded graphs the queue never held more than two levels
- **the first reach is the shortest.** say the shortest path to v has k edges, and w is the vertex before v on it, at distance k - 1. w comes out of the queue before anything at level k, and when it looks at v, v gets distance k from it, or had k already from another level-(k - 1) vertex. it can't get less: fewer than k edges would be a shorter path than the shortest
- **the mark goes on at the push.** a vertex gets `dist` and `parent` when it enters the queue, so it enters once. with the mark at the pop instead, a vertex enters once per neighbor that comes out before it: the queue needs room for 2m entries instead of n, and every repeat is a pop that does nothing. with the mark at the push, n slots and two indexes are the whole queue: `head` only moves forward, so nothing shifts, and `tail` never passes n
- **ties.** two vertices at level d that both touch v: the one that comes out first is the parent. 3 before 4 for 5 on the page's graph, (3, 2) before (4, 1) for (4, 2) on the maze. the order of the lists and the order of the pops decide it, so every tab builds the same tree
- **dist is the mark.** -1 means unseen, so there's no separate visited array: the distance and the visited bit are one number

## complexity

|                     | time     | space |
| ------------------- | -------- | ----- |
| adjacency lists     | O(n + m) | O(n)  |
| adjacency matrix    | O(n²)    | O(n)  |
| a list as the queue | O(n²)    | O(n)  |

every reached vertex comes out of the queue once, and every edge is looked at once from each end, or once when it's directed: n + 2m steps on a connected graph, O(n + m). on the page's graph that's 6 pops and 14 looks, 20 steps; on the maze 27 and 68, 95 steps. the space is past the graph itself: the queue, `dist` and `parent`, O(n). on an [adjacency matrix](/ds/graph/) the inner loop reads a whole row of n cells for every pop, however few edges there are: 42 steps on the page's graph, 6 pops and its 36 cells, and 972 on the maze, where each of the 27 pops reads a row of 35. a plain list as the queue adds a shift per pop: every item behind the front moves down a slot. on a star, with every other vertex on the center's list, a run from the center shifts (n - 1)(n - 2) / 2 items, 4,851 for 100 vertices: O(n²).

> **interactive figure:** a line chart of steps per vertex against how many vertices there are, from 16 to 4,096 on a doubling scale, with the top at 30 and a slider that picks a size and reads off every line. per vertex, a line that stays flat is linear time. bfs on adjacency lists, solid cyan, on random connected graphs with twice as many edges as vertices, sits at exactly 5 at every size: one pop and four looks per vertex. bfs on an open grid, dashed cyan, creeps from 4 at 16 cells to 4.94 at 4,096, since a cell on the edge of the grid has fewer neighbors. bfs on an adjacency matrix, amber, is n + 1 per vertex: 17 at 16, off the top before 32, 4,097 at 4,096. a plain list as the queue, dashed amber, is 8.38 at 16, 25.8 at 64, off the top before 128, and 1,109 at 4,096.

on 4,096 vertices and 8,192 edges, bfs took 20,480 steps: 4,096 pops and 16,384 looks. the matrix version took 16,781,312: the same 4,096 pops, and 16,777,216 cell reads. a plain list as the queue shifted 4,523,369 items on top of the 20,480 steps, more than 200 times the work of the search itself, because the queue gets wide: on a random graph the levels fan out fast, and this one had 1,715 vertices waiting at once, about 4 in 10. a grid is kinder to the list: on a 64 by 64 grid the queue is at most one diagonal, 64 cells, and the list shifts 172,641 items over the 20,224 steps of the search.

## implementations

each tab is the real file from the repo, checked by its tests (`go test`, `cargo test`, `vitest`, `make test`, `swift test`, `python -m unittest`), including the graph above, the maze as strings with a helper that turns it into lists, cells numbered row by row and neighbors in the order up, left, right, down, 2000 seeded graphs against relaxing every edge until nothing changes, and a line of 100,000 vertices. every tab uses the same queue, n slots with a head and a tail, marks a vertex when it enters, and takes neighbors in list order, so every tab builds the same tree and picks the same parent on a tie. the path comes back with the source first and the vertex last, and empty when there is no path. a vertex bfs never reached keeps -1 in typescript, go, c and python, `None` in rust and `nil` in swift. a source out of range: typescript throws a `RangeError` and python an `IndexError`, go and rust panic where it's used as an index, swift stops at a precondition, and c's `bfs_run` returns `false` with nothing left allocated.

`go/algos/bfs/bfs.go`

```go
// Package bfs is a reference breadth-first search: shortest paths by edge count, from one vertex. it
// explores a graph level by level with a queue: the source, then every vertex one edge away, then two, and
// so on. a vertex gets its distance and its parent the first time bfs reaches it, and that first time is
// along a shortest path: everything one level closer came out of the queue first.
package bfs

import "slices"

// Tree is what bfs finds from src: for every vertex, how many edges its shortest path takes and the vertex
// before it on that path. -1 means never reached, and src's parent is -1 too.
type Tree struct {
	Dist   []int
	Parent []int
}

// Search runs bfs over adjacency lists: vertices 0 to n - 1, with adj[u] listing u's neighbors. It follows
// adj as given, so directed lists work too, and it takes neighbors in list order, so every run from the
// same lists gives the same tree. A src outside 0 to n - 1 is a bug, and indexing with it panics.
func Search(adj [][]int, src int) Tree {
	n := len(adj)
	dist := make([]int, n)
	parent := make([]int, n)
	for v := range n {
		dist[v], parent[v] = -1, -1 // -1: not reached yet
	}
	// the queue: n slots, a head to take from and a tail to add at. a vertex enters once, when it gets its
	// distance, so n slots are enough, and nothing ever shifts
	queue := make([]int, n)
	head, tail := 0, 0
	dist[src] = 0
	queue[tail] = src
	tail++
	for head < tail {
		u := queue[head] // the front: the oldest vertex waiting
		head++
		for _, v := range adj[u] {
			if dist[v] != -1 {
				continue // reached already, by a path no longer than this one
			}
			dist[v] = dist[u] + 1
			parent[v] = u
			queue[tail] = v // the back: v waits its turn
			tail++
		}
	}
	return Tree{Dist: dist, Parent: parent}
}

// PathTo returns the shortest path from src to v, as vertices: src first, v last. It's empty when v was
// never reached, and just src for src itself. It follows parents back from v and reverses. A v outside the
// tree panics, as src does.
func (t Tree) PathTo(v int) []int {
	if t.Dist[v] == -1 {
		return nil
	}
	var path []int
	for u := v; u != -1; u = t.Parent[u] {
		path = append(path, u)
	}
	slices.Reverse(path)
	return path
}
```

`rust/algos/src/bfs.rs`

```rust
//! breadth-first search: shortest paths by edge count, from one vertex. it explores a graph level by level with a queue: the source, then every vertex one edge away, then two, and so on. a vertex gets its distance and its parent the first time bfs reaches it, and that first time is along a shortest path: everything one level closer came out of the queue first.

/// What bfs finds from src: for every vertex, how many edges its shortest path takes and the
/// vertex before it on that path. `None` means never reached, and src's parent is `None` too.
#[derive(Debug, PartialEq)]
pub struct BfsTree {
    pub dist: Vec<Option<usize>>,
    pub parent: Vec<Option<usize>>,
}

/// Breadth-first search over adjacency lists: vertices 0 to n - 1, with `adj[u]` listing `u`'s
/// neighbors. It follows `adj` as given, so directed lists work too, and it takes neighbors in
/// list order, so every run from the same lists gives the same tree. A `src` past n - 1 panics,
/// as any index out of range does: there's no check of its own.
pub fn bfs(adj: &[Vec<usize>], src: usize) -> BfsTree {
    let n = adj.len();
    let mut dist = vec![None; n];
    let mut parent = vec![None; n];
    // the queue: n slots, a head to take from and a tail to add at. a vertex enters once, when it
    // gets its distance, so n slots are enough, and nothing ever shifts
    let mut queue = vec![0; n];
    let (mut head, mut tail) = (0, 0);
    dist[src] = Some(0);
    queue[tail] = src;
    tail += 1;
    while head < tail {
        let u = queue[head]; // the front: the oldest vertex waiting
        head += 1;
        let d = dist[u].expect("a vertex in the queue has its distance");
        for &v in &adj[u] {
            if dist[v].is_some() {
                continue; // reached already, by a path no longer than this one
            }
            dist[v] = Some(d + 1);
            parent[v] = Some(u);
            queue[tail] = v; // the back: v waits its turn
            tail += 1;
        }
    }
    BfsTree { dist, parent }
}

/// The shortest path from src to `v`, as vertices: src first, `v` last. Empty when `v` was never
/// reached, and just src for src itself. It follows parents back from `v` and reverses. A `v` past
/// the tree's last vertex panics, as any index out of range does.
pub fn path_to(tree: &BfsTree, v: usize) -> Vec<usize> {
    if tree.dist[v].is_none() {
        return Vec::new();
    }
    let mut path = Vec::new();
    let mut at = Some(v);
    while let Some(u) = at {
        path.push(u);
        at = tree.parent[u];
    }
    path.reverse();
    path
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::panic::catch_unwind;

    /// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
    fn xorshift32(seed: u32) -> impl FnMut() -> usize {
        let mut state = seed;
        move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        }
    }

    /// Lists from edges in the order they went in, as the graph page builds them.
    fn lists_of(n: usize, edges: &[(usize, usize)]) -> Vec<Vec<usize>> {
        let mut adj = vec![Vec::new(); n];
        for &(u, v) in edges {
            adj[u].push(v);
            adj[v].push(u);
        }
        adj
    }

    /// Every shortest distance by relaxing every edge again and again, bellman-ford with every
    /// weight 1: the brute force.
    fn relaxed(adj: &[Vec<usize>], src: usize) -> Vec<Option<usize>> {
        let n = adj.len();
        let mut dist = vec![None; n];
        dist[src] = Some(0);
        for _ in 1..n {
            let mut changed = false;
            for u in 0..n {
                let Some(du) = dist[u] else { continue };
                for &v in &adj[u] {
                    if dist[v].is_none_or(|dv| du + 1 < dv) {
                        dist[v] = Some(du + 1);
                        changed = true;
                    }
                }
            }
            if !changed {
                break;
            }
        }
        dist
    }

    /// A maze as adjacency lists, with its size, its start and goal, and its walls.
    struct Grid {
        adj: Vec<Vec<usize>>,
        rows: usize,
        cols: usize,
        start: usize,
        goal: usize,
        walls: Vec<usize>,
    }

    /// A maze drawn as rows of text, split at whitespace: `s` the start, `g` the goal, `#` a wall,
    /// `.` open. Cell r, c is vertex r * cols + c. A wall's list is empty and no open cell lists
    /// it, and an open cell's neighbors come in the order up, left, right, down, skipping walls
    /// and the edge of the grid.
    fn grid_lists(picture: &str) -> Grid {
        let rows: Vec<&[u8]> = picture.split_whitespace().map(str::as_bytes).collect();
        let cols = rows[0].len();
        let open = |r: usize, c: usize| r < rows.len() && c < cols && rows[r][c] != b'#';
        let mut adj = Vec::new();
        let mut walls = Vec::new();
        let (mut start, mut goal) = (None, None);
        for (r, row) in rows.iter().enumerate() {
            for (c, &ch) in row.iter().enumerate() {
                let i = r * cols + c;
                match ch {
                    b's' => start = Some(i),
                    b'g' => goal = Some(i),
                    b'#' => {
                        walls.push(i);
                        adj.push(Vec::new());
                        continue;
                    }
                    _ => {}
                }
                let mut next_to = Vec::new();
                if r > 0 && open(r - 1, c) {
                    next_to.push(i - cols);
                }
                if c > 0 && open(r, c - 1) {
                    next_to.push(i - 1);
                }
                if open(r, c + 1) {
                    next_to.push(i + 1);
                }
                if open(r + 1, c) {
                    next_to.push(i + cols);
                }
                adj.push(next_to);
            }
        }
        Grid {
            adj,
            rows: rows.len(),
            cols,
            start: start.expect("an s"),
            goal: goal.expect("a g"),
            walls,
        }
    }

    // the graph page's graph: 6 vertices, 7 edges
    const EDGES: [(usize, usize); 7] = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 4), (3, 5), (4, 5)];

    // the page's maze. the goal is 10 steps away, where a straight line would be 6
    const MAZE: &str = "
        ...#.#.
        ...#.#.
        s..#.#g
        ...#.#.
        .......";

    #[test]
    fn the_graph_pages_graph_from_0_levels_0_1_1_2_2_3_and_every_parent_one_level_up() {
        let adj = lists_of(6, &EDGES);
        assert_eq!(
            adj,
            [
                vec![1, 2],
                vec![0, 2, 3],
                vec![0, 1, 4],
                vec![1, 5],
                vec![2, 5],
                vec![3, 4]
            ]
        );
        assert_eq!(
            bfs(&adj, 0),
            BfsTree {
                dist: vec![Some(0), Some(1), Some(1), Some(2), Some(2), Some(3)],
                parent: vec![None, Some(0), Some(0), Some(1), Some(2), Some(3)],
            }
        );
    }

    #[test]
    fn the_path_to_5_is_0_1_3_5_and_the_path_to_the_source_is_the_source_alone() {
        let tree = bfs(&lists_of(6, &EDGES), 0);
        assert_eq!(
            (path_to(&tree, 5), path_to(&tree, 0)),
            (vec![0, 1, 3, 5], vec![0])
        );
        // 5 is also 3 edges from 0 through 4, but 3 came out of the queue first and claimed it
        assert_eq!(path_to(&tree, 4), [0, 2, 4]);
    }

    #[test]
    fn one_vertex_and_no_edges_0_steps_from_itself_and_nothing_else_to_find() {
        let tree = bfs(&[vec![]], 0);
        assert_eq!(
            tree,
            BfsTree {
                dist: vec![Some(0)],
                parent: vec![None],
            }
        );
        assert_eq!(path_to(&tree, 0), [0]);
    }

    #[test]
    fn a_vertex_it_cant_reach_keeps_none_for_both_and_has_no_path() {
        // two pieces: 0 - 1, and 2 - 3
        let tree = bfs(&[vec![1], vec![0], vec![3], vec![2]], 0);
        assert_eq!(
            tree,
            BfsTree {
                dist: vec![Some(0), Some(1), None, None],
                parent: vec![None, Some(0), None, None],
            }
        );
        assert_eq!(
            [path_to(&tree, 2), path_to(&tree, 3), path_to(&tree, 1)],
            [vec![], vec![], vec![0, 1]]
        );
    }

    #[test]
    fn directed_lists_it_follows_adj_u_as_given_so_an_edge_runs_one_way() {
        // 0 → 1 → 2 → 0, and 3 → 1: 3 reaches everything, and nothing reaches 3
        let adj = [vec![1], vec![2], vec![0], vec![1]];
        assert_eq!(
            bfs(&adj, 0),
            BfsTree {
                dist: vec![Some(0), Some(1), Some(2), None],
                parent: vec![None, Some(0), Some(1), None],
            }
        );
        assert_eq!(
            bfs(&adj, 3),
            BfsTree {
                dist: vec![Some(3), Some(1), Some(2), Some(0)],
                parent: vec![Some(2), Some(3), Some(1), None],
            }
        );
        assert_eq!(
            (path_to(&bfs(&adj, 3), 0), path_to(&bfs(&adj, 0), 3)),
            (vec![3, 1, 2, 0], vec![])
        );
    }

    #[test]
    fn the_page_maze_the_goal_is_10_steps_away_through_the_gap_at_the_bottom_where_a_straight_line_is_6()
     {
        let Grid {
            adj,
            rows,
            cols,
            start,
            goal,
            walls,
        } = grid_lists(MAZE);
        assert_eq!((rows, cols, start, goal), (5, 7, 14, 20));
        assert_eq!(walls, [3, 5, 10, 12, 17, 19, 24, 26]);
        // neighbors in the order up, left, right, down: the start has no left, and (2, 2) has a
        // wall on its right
        assert_eq!(
            [adj[start].clone(), adj[16].clone(), adj[3].clone()],
            [vec![7, 15, 21], vec![9, 15, 23], vec![]]
        );
        let tree = bfs(&adj, start);
        assert_eq!(tree.dist[goal], Some(10));
        let cells: Vec<(usize, usize)> = path_to(&tree, goal)
            .into_iter()
            .map(|i| (i / cols, i % cols))
            .collect();
        assert_eq!(
            cells,
            [
                (2, 0),
                (2, 1),
                (2, 2),
                (3, 2),
                (4, 2),
                (4, 3),
                (4, 4),
                (4, 5),
                (4, 6),
                (3, 6),
                (2, 6)
            ]
        );
        // the levels, row by row, a wall drawn as #: a diamond around the start on the left, then
        // the corridors count up from the bottom
        let level = |d: &Option<usize>| d.map_or(" #".to_string(), |d| format!("{d:>2}"));
        let levels: Vec<String> = tree
            .dist
            .chunks(cols)
            .map(|row| row.iter().map(level).collect::<Vec<_>>().join(" "))
            .collect();
        assert_eq!(
            levels,
            [
                " 2  3  4  # 10  # 12",
                " 1  2  3  #  9  # 11",
                " 0  1  2  #  8  # 10",
                " 1  2  3  #  7  #  9",
                " 2  3  4  5  6  7  8",
            ]
        );
        for w in walls {
            assert_eq!(
                (tree.dist[w], tree.parent[w], path_to(&tree, w)),
                (None, None, vec![])
            );
        }
    }

    #[test]
    fn agrees_with_relaxing_every_edge_on_2000_seeded_graphs_and_every_parent_is_a_neighbor_one_level_up()
     {
        let mut next = xorshift32(42);
        for _ in 0..2000 {
            // random pairs, loops and repeats included: bfs has to shrug them off
            let n = 1 + next() % 30;
            let mut adj = vec![Vec::new(); n];
            for _ in 0..next() % (2 * n) {
                let (u, v) = (next() % n, next() % n);
                adj[u].push(v);
                adj[v].push(u);
            }
            let src = next() % n;
            let tree = bfs(&adj, src);
            assert_eq!(tree.dist, relaxed(&adj, src));
            assert_eq!((tree.dist[src], tree.parent[src]), (Some(0), None));
            for v in (0..n).filter(|&v| v != src) {
                let Some(dv) = tree.dist[v] else {
                    assert_eq!((tree.parent[v], path_to(&tree, v)), (None, vec![]));
                    continue;
                };
                let p = tree.parent[v].expect("a reached vertex has a parent");
                assert!(adj[p].contains(&v));
                assert_eq!(tree.dist[p], Some(dv - 1));
                // so the path back is a shortest path: one edge per level, src to v
                let path = path_to(&tree, v);
                assert_eq!(
                    (path.len(), path[0], path[path.len() - 1]),
                    (dv + 1, src, v)
                );
                assert!(path.windows(2).all(|step| adj[step[0]].contains(&step[1])));
            }
        }
    }

    #[test]
    fn a_vertex_out_of_range_panics_as_a_source_or_as_a_destination() {
        let adj = lists_of(6, &EDGES);
        let tree = bfs(&adj, 0);
        // a usize can't be -1 or 1.5, so past the end is the only bad vertex there is
        assert!(catch_unwind(|| bfs(&adj, 6)).is_err());
        assert!(catch_unwind(|| path_to(&tree, 6)).is_err());
        assert!(catch_unwind(|| bfs(&[], 0)).is_err());
    }

    #[test]
    fn a_line_of_100_000_vertices_the_far_end_is_99_999_steps_away_and_the_queue_never_has_to_grow()
    {
        let n = 100_000;
        let adj: Vec<Vec<usize>> = (0..n)
            .map(|v| {
                let mut next_to = Vec::new();
                if v > 0 {
                    next_to.push(v - 1);
                }
                if v + 1 < n {
                    next_to.push(v + 1);
                }
                next_to
            })
            .collect();
        let tree = bfs(&adj, 0);
        let path = path_to(&tree, n - 1);
        assert_eq!(
            (
                tree.dist[n - 1],
                tree.parent[n - 1],
                path.len(),
                path[0],
                path[n - 1]
            ),
            (Some(n - 1), Some(n - 2), n, 0, n - 1)
        );
    }
}
```

`site/src/visuals/bfs/bfs.ts`

```ts
/**
 * Breadth-first search: shortest paths by edge count, from one vertex. It explores a graph level by level with a
 * queue: the source, then every vertex one edge away, then two, and so on. A vertex gets its distance and its
 * parent the first time bfs reaches it, and that first time is along a shortest path: everything one level closer
 * came out of the queue first.
 */

/** What bfs finds from src: for every vertex, how many edges its shortest path takes and the vertex before it on
 * that path. -1 means never reached, and src's parent is -1 too. */
export type BfsTree = { dist: number[]; parent: number[] };

/**
 * Runs bfs over adjacency lists: vertices 0 to n - 1, with adj[u] listing u's neighbors. It follows adj as given,
 * so directed lists work too, and it takes neighbors in list order, so every run from the same lists gives the
 * same tree. A src outside 0 to n - 1 is a RangeError.
 */
export function bfs(adj: readonly (readonly number[])[], src: number): BfsTree {
  const n = adj.length;
  if (!Number.isInteger(src) || src < 0 || src >= n) throw new RangeError(`no vertex ${src}`);
  const dist = Array<number>(n).fill(-1);
  const parent = Array<number>(n).fill(-1);
  // the queue: n slots, a head to take from and a tail to add at. a vertex enters once, when it gets its
  // distance, so n slots are enough, and nothing ever shifts
  const queue = Array<number>(n).fill(0);
  let head = 0;
  let tail = 0;
  dist[src] = 0;
  queue[tail] = src;
  tail += 1;
  while (head < tail) {
    const u = queue[head]; // the front: the oldest vertex waiting
    head += 1;
    for (const v of adj[u]) {
      if (dist[v] !== -1) continue; // reached already, by a path no longer than this one
      dist[v] = dist[u] + 1;
      parent[v] = u;
      queue[tail] = v; // the back: v waits its turn
      tail += 1;
    }
  }
  return { dist, parent };
}

/**
 * The shortest path from src to v, as vertices: src first, v last. [] when v was never reached, and [src] for src
 * itself. It follows parents back from v and reverses. A v outside the tree is a RangeError.
 */
export function pathTo(tree: BfsTree, v: number): number[] {
  const { dist, parent } = tree;
  if (!Number.isInteger(v) || v < 0 || v >= dist.length) throw new RangeError(`no vertex ${v}`);
  if (dist[v] === -1) return [];
  const path: number[] = [];
  for (let u = v; u !== -1; u = parent[u]) path.push(u);
  return path.reverse();
}
```

`c/algos/bfs.c`

```c
/* breadth-first search: shortest paths by edge count, from one vertex. it explores a graph level by level with a queue: the source, then every vertex one edge away, then two, and so on. a vertex gets its distance and its parent the first time bfs reaches it, and that first time is along a shortest path: everything one level closer came out of the queue first. */
#include "bfs.h"

#include <stdlib.h>

/* the queue is an array of n slots with a head to take from and a tail to add at. a vertex enters
   once, when it gets its distance, so n slots are enough and nothing ever shifts. it's freed on the
   way out: the tree keeps only dist and parent. once src is below n, n is at least 1, so none of
   the mallocs is a malloc(0) */
bool bfs_run(BfsTree *tree, const size_t *const *adj, const size_t *len, size_t n, size_t src) {
    *tree = (BfsTree){0};
    if (src >= n) return false; /* no such vertex. with no vertices at all, 0 isn't one either */
    tree->dist = malloc(n * sizeof *tree->dist);
    tree->parent = malloc(n * sizeof *tree->parent);
    size_t *queue = malloc(n * sizeof *queue);
    if (!tree->dist || !tree->parent || !queue) {
        free(queue);
        bfs_free(tree); /* frees whichever of the two were allocated: free(NULL) does nothing */
        return false;
    }
    tree->n = n;
    for (size_t v = 0; v < n; v++) tree->dist[v] = tree->parent[v] = -1; /* nothing reached yet */
    size_t head = 0, tail = 0;
    tree->dist[src] = 0;
    queue[tail++] = src;
    while (head < tail) {
        size_t u = queue[head++]; /* the front: the oldest vertex waiting */
        for (size_t i = 0; i < len[u]; i++) {
            size_t v = adj[u][i];
            if (tree->dist[v] != -1) continue; /* reached already, by a path no longer than this one */
            tree->dist[v] = tree->dist[u] + 1;
            tree->parent[v] = (int)u;
            queue[tail++] = v; /* the back: v waits its turn */
        }
    }
    free(queue);
    return true;
}

void bfs_free(BfsTree *tree) {
    free(tree->dist);
    free(tree->parent);
    *tree = (BfsTree){0}; /* no vertices */
}

/* follows parents from v back to the source, writing as it goes, then reverses out in place so the
   source comes first. a reached v writes itself at least, so k is 1 or more and k - 1 can't wrap */
bool bfs_path_to(const BfsTree *tree, size_t v, size_t *out, size_t *count) {
    *count = 0;
    if (v >= tree->n) return false; /* no such vertex */
    if (tree->dist[v] == -1) return true; /* never reached: no path */
    size_t k = 0;
    for (int u = (int)v; u != -1; u = tree->parent[u]) out[k++] = (size_t)u;
    for (size_t i = 0, j = k - 1; i < j; i++, j--) {
        size_t t = out[i];
        out[i] = out[j];
        out[j] = t;
    }
    *count = k;
    return true;
}
```

`swift/algos/BFS.swift`

```swift
/// breadth-first search: shortest paths by edge count, from one vertex. it explores a graph level by level with a queue: the source, then every vertex one edge away, then two, and so on. a vertex gets its distance and its parent the first time bfs reaches it, and that first time is along a shortest path: everything one level closer came out of the queue first.

/// what bfs finds from src: for every vertex, how many edges its shortest path takes and the vertex before it on
/// that path. nil means never reached, and src's parent is nil too
public struct BFSTree {
    public let dist: [Int?]
    public let parent: [Int?]

    /// the shortest path from src to v, as vertices: src first, v last. [] when v was never reached, and [src] for
    /// src itself. it follows parents back from v and reverses. a v outside the tree traps
    public func path(to v: Int) -> [Int] {
        precondition(0 <= v && v < dist.count, "no vertex \(v)")
        if dist[v] == nil { return [] }
        var path = [v]
        while let p = parent[path.last!] { path.append(p) } // src has no parent, so the walk stops there
        return path.reversed()
    }
}

/// bfs over adjacency lists: vertices 0 to n - 1, with adj[u] listing u's neighbors. it follows adj as given, so
/// directed lists work too, and it takes neighbors in list order, so every run from the same lists gives the same
/// tree. a src outside 0 to n - 1 traps
public func bfs(_ adj: [[Int]], _ src: Int) -> BFSTree {
    let n = adj.count
    precondition(0 <= src && src < n, "no vertex \(src)")
    var dist = [Int?](repeating: nil, count: n)
    var parent = [Int?](repeating: nil, count: n)
    // the queue: n slots, a head to take from and a tail to add at. a vertex enters once, when it gets its
    // distance, so n slots are enough, and nothing ever shifts
    var queue = [Int](repeating: 0, count: n)
    var head = 0
    var tail = 0
    dist[src] = 0
    queue[tail] = src
    tail += 1
    while head < tail {
        let u = queue[head] // the front: the oldest vertex waiting
        head += 1
        for v in adj[u] {
            if dist[v] != nil { continue } // reached already, by a path no longer than this one
            dist[v] = dist[u]! + 1 // u got its dist when it went in
            parent[v] = u
            queue[tail] = v // the back: v waits its turn
            tail += 1
        }
    }
    return BFSTree(dist: dist, parent: parent)
}
```

`python/algos/bfs.py`

```python
"""breadth-first search: shortest paths by edge count, from one vertex. it explores a graph level by level with a queue: the source, then every vertex one edge away, then two, and so on. a vertex gets its distance and its parent the first time bfs reaches it, and that first time is along a shortest path: everything one level closer came out of the queue first."""

from __future__ import annotations

from typing import NamedTuple


class BfsTree(NamedTuple):
    """What bfs finds from src.

    dist[v] is how many edges v's shortest path takes, and parent[v] is the vertex before v on that path. -1
    means never reached, and src's parent is -1 too.
    """

    dist: list[int]
    parent: list[int]


def bfs(adj: list[list[int]], src: int) -> BfsTree:
    """Run bfs over adjacency lists: vertices 0 to n - 1, with adj[u] listing u's neighbors.

    It follows adj as given, so directed lists work too, and it takes neighbors in list order, so every run
    from the same lists gives the same tree. A src outside 0 to n - 1 raises IndexError.
    """
    n = len(adj)
    if not 0 <= src < n:
        raise IndexError(f"no vertex {src}")  # a negative src would count from the end of the list
    dist = [-1] * n
    parent = [-1] * n
    # the queue: n slots, a head to take from and a tail to add at. a vertex enters once, when it gets its
    # distance, so n slots are enough, and nothing ever shifts. a list's pop(0) would shift every item left
    queue = [0] * n
    head = 0
    tail = 0
    dist[src] = 0
    queue[tail] = src
    tail += 1
    while head < tail:
        u = queue[head]  # the front: the oldest vertex waiting
        head += 1
        for v in adj[u]:
            if dist[v] != -1:
                continue  # reached already, by a path no longer than this one
            dist[v] = dist[u] + 1
            parent[v] = u
            queue[tail] = v  # the back: v waits its turn
            tail += 1
    return BfsTree(dist, parent)


def path_to(tree: BfsTree, v: int) -> list[int]:
    """Return the shortest path from src to v, as vertices: src first, v last.

    [] when v was never reached, and [src] for src itself. It follows parents back from v and reverses.
    A v outside the tree raises IndexError.
    """
    dist, parent = tree
    if not 0 <= v < len(dist):
        raise IndexError(f"no vertex {v}")
    if dist[v] == -1:
        return []
    path = []
    u = v
    while u != -1:
        path.append(u)
        u = parent[u]
    path.reverse()
    return path
```

## pitfalls

- **marking when it comes out.** the mark goes on when a vertex enters the queue. put it on at the pop and the same vertex enters once per neighbor that comes out before it: the queue holds up to 2m entries instead of n, every repeat is a pop that does nothing, and an array of n slots overflows
- **a plain list as the queue.** `pop(0)` in python moves every other item down a slot, O(n) a pop,[^deque] and javascript's `shift()` is specified the same way.[^shift] on the chart that's 4,523,369 shifts on 4,096 vertices, more than 200 times the work of the search. python's `collections.deque` pops from the left in O(1),[^deque] and n slots with a head and a tail do it in any language
- **weighted edges.** bfs counts edges. two edges of weight 1 beat one edge of weight 5, and bfs says the opposite. for weights, dijkstra
- **stopping too late, or too early.** when one target is all you need, stop the moment it gets its distance: in bfs that number is final when the vertex enters the queue. on the maze the goal gets its 10 when the 23rd cell comes out, and the run goes on for 4 more pops that can't change it. the other way round is the trap in 0-1 bfs and in dijkstra: there a distance can still drop after the vertex enters the queue, and only the pop makes it final, so stopping at the push is too early
- **the wrong direction.** bfs follows the lists as given. on a directed graph, the distances from s say what s reaches. to find what reaches t, run it from t on the reversed edges
- **a path read backwards.** parents point toward the source, so walking them from v gives the path back to front: reverse it. and check `dist[v]` first, since a vertex that was never reached has no parent to follow

## variants

- **multi-source bfs.** put every source in the queue at the start, all at distance 0, and every vertex gets its distance to the nearest source in one run. rotting oranges and 01 matrix are this. networkx's `bfs_layers` takes a list of sources[^networkx]
- **0-1 bfs.** edges of weight 0 and 1, and a deque instead of a queue: a neighbor across a 0-edge goes on the front, across a 1-edge on the back, and a vertex's distance can drop until it comes out. O(n + m), where dijkstra would pay a log
- **bidirectional bfs.** search from both ends and stop when the two floods meet. with b neighbors per vertex and the target d levels out, one flood touches about b^d vertices and two half floods about 2 b^(d/2). word ladder is the classic
- **on a grid.** no lists at all: a cell's neighbors come from its row and column, four or eight of them, and walls are skipped. the stepper's maze is this, and so is every flood fill
- **level order.** to handle a tree one level at a time, take the queue's length at the top of each round and pop exactly that many: those are one level. binary tree level order traversal
- **components.** run bfs from every vertex that has no distance yet. each run is one connected component, and the number of runs is how many there are. [union-find](/ds/union-find/) answers the same question without walking the graph
- **dijkstra and a\*.** swap the queue for a min-heap keyed by distance and bfs becomes dijkstra, for weighted edges; add an estimate of the distance left and it's a\*. boost's `breadth_first_search` takes the queue as a parameter for this reason: a priority queue in its place gives dijkstra[^boost]

## practice

- [binary tree level order traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/): one level per round
- [rotting oranges](https://leetcode.com/problems/rotting-oranges/): multi-source bfs on a grid, and the levels are minutes
- [shortest path in binary matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/): the maze, with eight neighbors
- [01 matrix](https://leetcode.com/problems/01-matrix/): multi-source bfs from every 0
- [word ladder](https://leetcode.com/problems/word-ladder/): bfs over words, where a neighbor is one letter changed
- [open the lock](https://leetcode.com/problems/open-the-lock/): bfs over 10,000 states with 8 neighbors each, and the deadends are walls

## how real libraries do it

- **python.** the standard library has no bfs. the queue is `collections.deque`: appends and pops at either end in about O(1), where a list pays O(n) of memory movement for `pop(0)`[^deque]. networkx's `single_source_shortest_path_length` has no queue at all: it keeps the current level in one list and builds the next in another, with a `seen` set, and yields each vertex with its level. its `bfs_edges` keeps a pair per vertex, the vertex and an iterator over its neighbors, one list of pairs per level, and yields each tree edge as it finds it; the code came from david eppstein's pads. `bfs_layers` yields one list per level and takes several sources[^networkx]
- **rust.** petgraph's `Bfs` is a visitor you call `next` on: a `VecDeque` of vertices to visit, which it calls `stack`, and a `discovered` map. `new` marks the start discovered and pushes it; `next` pops the front, marks and pushes each neighbor that wasn't discovered yet, and hands back the popped vertex[^petgraph]
- **c++.** boost graph's `breadth_first_search` keeps a color per vertex: white for undiscovered, gray for discovered and in the queue, black for done. a vertex turns gray when it's pushed and black once its out-edges are examined. the docs put the complexity at O(E + V) and let you swap the queue, a priority queue giving dijkstra[^boost]
- **go, swift, c.** nothing in the standard libraries. it's a loop of a dozen lines over whatever holds the edges

[^history]: edward f. moore, _the shortest path through a maze_, in the proceedings of an international symposium on the theory of switching, harvard university press, 1959, pages 285 to 292; and c. y. lee, [an algorithm for path connections and its applications](https://doi.org/10.1109/TEC.1961.5219222), ire transactions on electronic computers, ec-10(3), pages 346 to 365, 1961.

[^deque]: [collections.rst](https://github.com/python/cpython/blob/v3.15.0/Doc/library/collections.rst#L463-L476) in cpython 3.15.0: deques support memory-efficient appends and pops from either side with approximately the same O(1) performance in either direction, while lists are optimized for fast fixed-length operations and pay O(n) of memory movement for `pop(0)` and `insert(0, v)`. the tutorial's [using lists as queues](https://github.com/python/cpython/blob/v3.15.0/Doc/tutorial/datastructures.rst#L163-L174) says the same: pops from the beginning of a list are slow, because every other element has to be shifted by one, so a queue should be a `collections.deque`.

[^shift]: [array.prototype.shift](https://tc39.es/ecma262/2026/multipage/indexed-collections.html#sec-array.prototype.shift) in the ecmascript 2026 language specification: the steps read the first element, then move each element from index k to k - 1 for every k from 1 to the last index, so one shift touches the whole array. the spec's [algorithm conventions](https://tc39.es/ecma262/2026/multipage/notational-conventions.html#sec-algorithm-conventions) say steps like these fix the result, not the technique: an engine may use a faster algorithm.

[^networkx]: networkx 3.7. [unweighted.py](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/shortest_paths/unweighted.py#L83-L113): `_single_shortest_path_length`, which `single_source_shortest_path_length` [calls with the source as the first level](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/shortest_paths/unweighted.py#L79-L80), keeps a `seen` set and two lists, `thislevel` and `nextlevel`: every unseen neighbor of this level joins the next and is yielded with the level number, and it returns early once every node is seen. [breadth_first_search.py](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/traversal/breadth_first_search.py#L86-L107): `generic_bfs_edges` keeps a `seen` set and a list of (parent, children iterator) pairs per depth, yields each (parent, child) edge the first time the child is seen, and [credits](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/traversal/breadth_first_search.py#L77-L83) the implementation to pads, which was in the public domain when first accessed in july 2004. [`bfs_layers`](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/traversal/breadth_first_search.py#L430-L484) takes one source or several, keeps a `visited` set and the current layer as a list, and yields one list of nodes per distance.

[^petgraph]: [traversal.rs](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/visit/traversal.rs#L226-L309) in petgraph 0.8.3: `Bfs` traverses only the nodes reachable from its start and isn't recursive. it holds a `VecDeque` named `stack`, documented as the queue of nodes to visit, and a `discovered` visit map; `new` marks the start discovered and pushes it, and `next` pops the front, pushes each neighbor whose `visit` call says it's new, and returns the popped node.

[^boost]: boost 1.92.0. [breadth_first_search.adoc](https://github.com/boostorg/graph/blob/boost-1.92.0/doc/modules/ROOT/pages/algorithms/traversal/breadth_first_search.adoc#L154-L193): bfs uses a color marker per vertex and a queue; white vertices are undiscovered, gray ones discovered with undiscovered neighbors, black ones discovered with only black or gray neighbors; a vertex comes out of the queue, each undiscovered neighbor turns gray and goes in, and the vertex turns black once its out-edges are examined. [the top of the page](https://github.com/boostorg/graph/blob/boost-1.92.0/doc/modules/ROOT/pages/algorithms/traversal/breadth_first_search.adoc#L1-L7) gives the complexity as O(E + V), and [the queue parameter](https://github.com/boostorg/graph/blob/boost-1.92.0/doc/modules/ROOT/pages/algorithms/traversal/breadth_first_search.adoc#L46-L53) says a fifo queue gives the usual bfs order and other queues change it, dijkstra's algorithm being a priority queue in its place. [breadth_first_search.hpp](https://github.com/boostorg/graph/blob/boost-1.92.0/include/boost/graph/breadth_first_search.hpp#L71-L104) is that loop: sources turn gray and are pushed, each popped vertex's white targets turn gray and are pushed, and the vertex turns black.

## related

- https://learning.anthnydas.com/ds/graph.md
- https://learning.anthnydas.com/ds/stack-queue.md
- https://learning.anthnydas.com/algos/dfs.md
- https://learning.anthnydas.com/algos/dijkstra.md
- https://learning.anthnydas.com/algos/a-star.md
