algosgraphs

bfs

explore a graph level by level with a queue.

report a mistake
.md

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*
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the queue, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

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

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.

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.

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.1 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.

a maze: start to goal
0

tap a cell to make it a wall, or a wall to open it. the figure jumps to the end of the new run.

(2, 0)

(2, 0) is the source, 0 steps from itself. it goes into the queue. nothing else is reached yet

out of the queue
0
looks
0
level
0
step
1 of 98
pseudocode
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

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.

1 just came out of the queue, which holds 2. bfs looks at its 3 neighbors, 0, 2, 3. what's in the queue after?

012345011
2

pick one.

0 / 0 right

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

pseudocode
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

the queue on the page's graph after each pop, front first
outthe queue after its neighborslevels
0121
1231 then 2
2342
3452 then 3
453
5emptynone
  • out: the vertex that just came out of the front
  • cyan: the level coming out now, at the front
  • amber: one level further, behind it

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.

complexity

timespace
adjacency listsO(n + m)O(n)
adjacency matrixO(n²)O(n)
a list as the queueO(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 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²).

0102030162564096matrixlist as the queue
lists
5 steps per vertex
open grid
4.94 steps per vertex
matrix
4,097 steps per vertex
list as the queue
1,109 steps per vertex

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
// 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
//! 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
/**
 * 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
/* 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
/// 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
"""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

variants

practice

how real libraries do it

sources

  1. 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 (opens in a new tab), ire transactions on electronic computers, ec-10(3), pages 346 to 365, 1961. ↩

  2. collections.rst (opens in a new tab) 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 (opens in a new tab) 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. ↩ ↩2 ↩3

  3. array.prototype.shift (opens in a new tab) 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 (opens in a new tab) say steps like these fix the result, not the technique: an engine may use a faster algorithm. ↩

  4. networkx 3.7. unweighted.py (opens in a new tab): _single_shortest_path_length, which single_source_shortest_path_length calls with the source as the first level (opens in a new tab), 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 (opens in a new tab): 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 (opens in a new tab) the implementation to pads, which was in the public domain when first accessed in july 2004. bfs_layers (opens in a new tab) takes one source or several, keeps a visited set and the current layer as a list, and yields one list of nodes per distance. ↩ ↩2

  5. boost 1.92.0. breadth_first_search.adoc (opens in a new tab): 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 (opens in a new tab) gives the complexity as O(E + V), and the queue parameter (opens in a new tab) 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 (opens in a new tab) 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. ↩ ↩2

  6. traversal.rs (opens in a new tab) 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. ↩