Breadth-First Search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at a selected node (often referred to as the β€˜root’ in trees) and explores all of its neighboring nodes at the present depth prior to moving on to nodes at the next depth level.

Properties

  • For each consists of all nodes at distance exactly edges from .
  • There is a path from to .

Formal Definition

BFS can be formally defined as follows:

Let the graph be G = (V, E) and the start vertex be s ∈ V.

Define the distance (in number of edges) from s:

Define a predecessor function that induces a BFS tree:

The BFS tree is:

Correctness (shortest-path property):

Complexity (with adjacency lists):

Pseudocode