The idea
Key formulas
Shortest-path distance in an unweighted graph
Visit each discovered vertex once
Loading lessons…
Just a moment, getting everything ready. The first load can take up to a minute.
Data structures and algorithms
Compare BFS queue order with DFS stack order on a seeded random graph, including disconnected components.
Breadth-first search explores neighbors in layers using a queue. Depth-first search follows a branch using a stack before backtracking. Marking vertices when discovered prevents duplicate work; restarting at unvisited vertices covers disconnected graphs.
The graph and neighbor order are deterministic for a given seed. BFS finds shortest paths by edge count in an unweighted graph; DFS does not promise that.