Breadth-First Search

A graph traversal algorithm that explores vertices in layers.

Time Complexity

O(V + E)

?

Space Complexity

O(V)

?

In-Place

No

No

Stability

Yes

Yes

Difficulty

Medium

★★★☆☆

Description

Breadth-First Search (BFS) is a graph traversal algorithm that explores all neighbors of a vertex before moving to the next level.

It uses a queue to keep track of the next vertex to visit, making it ideal for finding the shortest path in unweighted graphs.

Steps:

  1. Start from a source vertex
  2. Visit all its neighbors
  3. Then visit the neighbors’ neighbors, and so on

BFS guarantees the shortest path in terms of the number of edges in unweighted graphs.

Computational Complexity

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

Implementation