Graph
Graph
Graph Traversal:
Color:
White: (vertex is not visited/discovered). A vertex is said to be discovered when first time it is
encountered during the search.
Gray: (vertex is visited/discovered. May have some undiscovered adjacent vertices)
Black: (vertex is visited/discovered and all adjacent vertices are also discovered)
d:
Distance from source vertex to the given vertex. For a weighted graph this distance will be
the weight of edges from source vertex and for unweighted graph this distance will be the
number of edges from the source vertex.
π:
Predecessor/parent vertex.
Main idea:
Given a graph “G” and source vertex “s”. Initially all the vertices in the graph are unvisited so set the
attributes of each vertex i.e., (color = white, d = ∞, π = NULL) since we don’t know the number of
edges from source vertex to all other vertices, so we are initializing them with infinity. Similarly, we
don’t know the predecessor/parent of each vertex so initialized with NULL.
Now start traversing from source vertex so update the attributes of source vertex i.e., (color = gray, d
= 0). Create a queue an insert the source vertex in the queue.
Iterate until the queue is not empty. In every iteration of the loop perform the following steps:
• remove the vertex from the queue (dequeue operation)
• check all the adjacent vertices of the removed vertex and if any of the adjacent vertex is
undiscovered/unvisited yet then update the attributes of that undiscovered adjacent vertex
i.e., (color = gray, etc.) and then insert that vertex back into the queue.
• Once all the adjacent vertices of the removed vertex are discovered then update the “color”
attribute to black.