Graph Theory37 sections · 1633 units
Open in Course

Complexity of BFS

Time and Space

BFS visits each node once and examines each edge once. If the graph has VV nodes and EE edges, BFS runs in O(V+E)O(V + E) time. Queue operations (push and pop) take O(1)O(1) each. Marking nodes as visited takes O(1)O(1) per node. The space complexity is O(V)O(V) for the queue and visited array.

In the worst case, all nodes could be in the queue at once. For a grid, V=rows×colsV = rows \times cols and EE is about 4V4V (or 8V8V with diagonals), so BFS runs in O(rows×cols)O(rows \times cols) time.