Breadth-First (BFS) Traversal of graphs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.