Breadth-first search (BFS) start from the root node and explores all
the neighbouring nodes.
Then for each of those nearest nodes, it explores their neighbour
nodes, and so on, until it finds the goal.
Breadth-first search can be used to solve many problems in graph
theory, for example:
Finding all nodes within one connected components.
Finding the shortest path between two nodes u and v .
Testing a graph for bipartiteness.
Discovered but not fully explored-grey colour
Fully explored.-black colour
How It Works?
Pick a source vertex S to start.
Find (or discover) the vertices that are adjacent to S.
Pick each child of S in turn and discover their vertices adjacent
to that child.
Done when all children have been discovered and examined.
The breadth-first search uses a FIFO queue.
Algorithm BFS(s )
1. color all the vertices white
2. initialize an empty queue Q
3. for each neighbor v of s
4. insert v in Q ; color [v ] = grey
5. output s ; color [s ] = black
6. while Q is not empty
7. u = top of Q ; remove u from Q
8. for each neighbor v of u
9. if color [v ] = white
10. insert v in Q ; color [v ] = grey
11. output u; color [u] = black