BFS
Breadth-first search walks a graph level by level using a queue. On an unweighted graph, the first time you reach a node is a shortest path in number of edges.
Detailed Explanation
BFS starts at a source, visits all neighbours, then their neighbours, and so on. The structure is a queue: VecDeque with push_back for newly discovered nodes and pop_front for the node you expand. A visited set (or a Vec<bool> if nodes are 0..n) prevents enqueueing a node twice.
The first time you mark a node visited should be when you enqueue it, not when you dequeue it. Otherwise the same node can sit in the queue many times and you lose the O(V + E) bound. Store parent pointers or distances in a parallel Vec if you need the path, not only reachability.
BFS is the algorithm for unweighted shortest path, for "are these two users connected within k hops", and for level-order tree traversal. It is the wrong algorithm for a weighted graph (use Dijkstra / a BinaryHeap) and the wrong algorithm if you only need any path or a topological property that DFS finds more directly.
In Rust, represent the graph as Vec<Vec<usize>> for adjacency lists, or a HashMap<T, Vec<T>> for arbitrary node ids. Borrow the adjacency list and own the queue and the visited set. Do not fight recursive BFS; BFS is iterative. Recursion would be the wrong stack.
When you reach for BFS: unweighted shortest path, levels, "nearest" in a grid. When you reach for DFS: connectivity, cycles, topological sort, path existence without distance. When you reach for a heap: weights on edges.
Grids are graphs. A cell (r, c) has four (or eight) neighbours, and the same visited rule applies: mark when you enqueue, store a parent or a distance grid if you need the path, and stop when the queue is empty or when you first reach the target. A VecDeque of coordinates plus a Vec<Vec<bool>> is the usual Rust spelling. Do not recurse; a large maze will overflow the stack.
Code Examples
use std::collections::VecDeque;
fn bfs(adj: &[Vec<usize>], start: usize) -> Vec<bool> {
let mut seen = vec![false; adj.len()];
let mut q = VecDeque::new();
seen[start] = true;
q.push_back(start);
while let Some(u) = q.pop_front() {
for &v in &adj[u] {
if !seen[v] {
seen[v] = true;
q.push_back(v);
}
}
}
seen
}
fn main() {
let adj = vec![vec![1, 2], vec![0], vec![0]];
println!("{:?}", bfs(&adj, 0)); // prints: [true, true, true]
}Common Gotchas
Mark visited at enqueue time
Marking at dequeue lets a node be queued once per incoming edge and turns a large graph into a time bomb.
A `Vec` stack is DFS, a `VecDeque` queue is BFS
Swapping `pop` and `pop_front` is a one-word bug with a completely different traversal.
Grids need bounds checks
Four-neighbour BFS on a matrix must reject negative indices. Use `usize` carefully or store `i32` coordinates.
Weighted graphs need a different algorithm
BFS counts edges, not lengths. A `BinaryHeap` Dijkstra is the usual next step.