Breadth-First Search

BFS on an undirected graph from a source vertex. Reads the Algs4 Graph format (V, then E, then the edges). Watch the FIFO queue advance and the graph fill in by distance layers — BFS finds shortest paths in edges. Flip on Water mode to watch a flood spread from the source at one edge per unit time.

650ms
Graph G
undiscovered
in queue
current source
water (flowing)
buoy (reached)
distance: near → far
Status
Press  Step  or  Play  to begin.
Queue  ·  FIFO
front ▸
empty
◂ back
Front is dequeued next; new neighbours join the back. FIFO order is what makes BFS explore by layers.
Distance layers
none yet
Adjacency lists  ·  iterators
Edit / paste a graph
Format (Sedgewick & Wayne Graph): first line is the number of vertices V, second line is the number of edges E, then E lines each holding an undirected edge v w. Vertices are 0 … V−1. Parallel edges and self-loops are allowed. Adjacency lists are built by prepending (a Sedgewick Bag), so a vertex's neighbours appear in reverse order of how the edges were read — matching the booksite traversal order.