algo·visual

BFS (Graph)

Graphs
avgO(V + E)worstO(V + E)spaceO(V)
A0BCDEFGH

Start at A: mark it seen and put it in the queue

1 / 30
Nodes8
Source
Edges

How it works

Breadth-first search visits the source, then all of its neighbours, then their unseen neighbours, using a FIFO queue. Nodes come out in order of hop distance from the source, and the edges that discover new nodes form a shortest-path tree.

Complexity

Best
O(V + E)
Average
O(V + E)
Worst
O(V + E)
Space
O(V)

Search algorithms

Jump to any algorithm or page