Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some subjective node of a graph, sometimes referred to as a ‘search key’) and explores the neighbor nodes first, before moving to the next level neighbors.
BFS was invented in the late 1950s by E. F. Moore, who used it to find the shortest path out of a maze, and discovered independently by C. Y. Lee as a wire routing algorithm.
So traversal is: a, b, c, d, e, f, g, h, i , j, k.
Pseudocode:
Input: A graph Graph and a starting vertex root of G
Output: All vertices reachable from root labeled as explored.
A non-recursive implementation of breadth-first search:
1 Breadth-First-Search (Graph, root):
2
3 for each node n in Graph:
4 n.distance = INFINITY
5 n.parent = NIL
6
7 create empty queue Q
8
9 root.distance = 0
10 Q.enqueue(root)
11
12 while Q is not empty:
13
14 current = Q.dequeue()
15
16 for each node n that is adjacent to current:
17 if n.distance == INFINITY:
18 n.distance = current.distance + 1
19 n.parent = current
20 Q.enqueue(n)
Applications:
Breadth-first search can be used to solve many problems in graph theory, for example:
• Shortest Path and Minimum Spanning Tree for unweighted graph.
• Peer to Peer Networks.
• Social Networking Websites.
• In Garbage Collection.
• Path Finding.
• Finding all nodes within one connected component.