The breadth-first search algorithm
We'll cover the following...
Breadth-first search assigns two values to each vertex
A distance, giving the minimum number of edges in any path from the source vertex to vertex
. The predecessor vertex of
along some shortest path from the source vertex. The source vertex's predecessor is some special value, such as null, indicating that it has no predecessor.
If there is no path from the source vertex to vertex
For example, here's an undirected graph with eight vertices, numbered
In BFS, we initially set the distance and predecessor of each vertex to the special value (null). We start the search at the source and assign it a distance of
Given the example above, here are the steps plus a visualization to play through each step:
Start by visiting vertex
, the source, setting its distance to . Then visit vertices
...