Breadth-First Search (BFS)
Breadth-First Search (BFS)
Breadth-First Search (BFS) is one of the simplest and most important graph-search algorithms. BFS systematically explores all vertices that are reachable from a given source vertex s.
The main idea is to explore the graph level by level, starting from the source.
Basic idea
Suppose the source is s.
BFS first discovers:
- s — distance 0
- All neighbors of s — distance 1
- All undiscovered neighbors of those vertices — distance 2
- Then vertices at distance 3, and so on.
Thus, BFS can be viewed as a series of waves expanding outward from the source.
Distance 0: s Distance 1: A B C Distance 2: D E F G Distance 3: H I
The distance of a vertex is the minimum number of edges required to reach it from the source.
Queue-Based Exploration
BFS uses a FIFO (First-In, First-Out) queue.
The queue contains the vertices that have been discovered but whose adjacency lists have not yet been completely explored.
BFS uses three colors:
- WHITE – vertex has not yet been discovered.
- GRAY – vertex has been discovered and is currently on the frontier.
- BLACK – all its adjacent vertices have been examined.
The process is:
WHITE → GRAY → BLACK
For example:
Undiscovered | WHITE ↓ Discovered | GRAY ↓ All neighbors examined | BLACK
Breadth-First Tree
BFS also constructs a breadth-first tree rooted at the source vertex.
Whenever BFS discovers a new vertex v while examining vertex u, it records:
v.parent = u
and adds the edge (u,v) to the BFS tree.
For example:
s / \ A B / \ \ C D E
The path from s to any reachable vertex in this BFS tree corresponds to a shortest path in the original graph, where the length is measured by the number of edges.
For example:
s → A → D
is a shortest path from s to D.
Important Properties of BFS
1. Finds all reachable vertices
BFS discovers every vertex that can be reached from the source.
Vertices that cannot be reached from s remain WHITE.
2. Computes shortest-path distances
For every reachable vertex v:
v.d
stores the minimum number of edges from s to v.
Thus:
s.d = 0
and if v is first discovered from u:
v.d = u.d + 1
3. Constructs a shortest-path tree
The predecessor attribute:
v.π
stores the parent of v in the BFS tree.
4. Uses a FIFO queue
The queue ensures that vertices are processed in increasing order of their distance from the source.
Comments
Post a Comment