Breadth-First search systematically explores the edges in Figure g to discover all the nodes that can be reached from the source node S. The algorithm is able to calculate the minimum number of edges from the source node to all the nodes that can be reached.
All the nodes were painted white at the beginning. These nodes may turn gray or black during the algorithm's propulsion process. In the search process, the first time a node is encountered is called the node is discovered, the color of the node will change.
In order to understand or debug the algorithm, we used the Gray representative to have found but not yet explored the adjacency edge (out edge), with the black representative already discovered and completed exploring the adjacency edge. There is no need to distinguish between grey and black nodes in practical applications.
A breadth-first search tree is constructed during the execution of a breadth-first search. Initially, the tree contains only the root nodes (the source node). When you scan an adjacent linked list that has found node V, you add a subtree of V to the breadth precedence tree whenever a white node U is found. The queue used in the algorithm is actually the sequence traversal of the breadth-first search tree.
voidGRAPH::BFS (intsorce_id) {Vertice* Source =0; for(Node node:allvertices) {if(Node.first = =sorce_id) {Source=Node.second; Node.second->color =GRAY; Node.second->distance =0; Continue; } Node.second->color =White ; } Queue<Vertice*> q = queue<vertice*>(); Q.push (source); while(!Q.empty ()) {Vertice* v =Q.front (); Q.pop (); for(Edge e:v->adjacentvertices) {Vertice* U =E.target; if(U->color = =White ) {u->color =GRAY; U->begin = (U->begin = =0) ? v->begin+1: u->begin; Q.push (U); }} v->color =BLACK; }}
Breadth-First (BFS) Traversal of graphs