Depth-first traversal and breadth-first traversal of graphs with adjacency tables as storage structures (C + +)

Source: Internet
Author: User

First, the storage of graphs

Using the Adjacency table method to store the graph, the storage structure is divided into two parts, one is an array of all the vertices of the graph, and the other part is the linked list that is attached to each element of the array to represent the vertex's adjacency point.

1. The structure unit for storing vertices is:

class vnode{public:    string  nodename;     BOOL visted;//The duration of the graph is used to mark whether the graph    has been accessed *Next;    Vnode ()    {        false;         = NULL;    }};

The structural units of the linked list are:

class node{public:    string  nodename;     int Index of the nodeindex;//node to quickly position    the node in the vertex array int weight;//weights, used to store information    between vertices *next;     = NULL;}};

2. Now declare graph this class, the declaration of the class is (the member function about the traversal of the graph is also included):

class graph{public:    Graph ();                     ~Graph ();     BOOL Deepfirstsearch (int  nodeindex);     void clearvisited ();     BOOL Widefirstsearch (int nodeindex); protected :     *Pvnode;     int Vnumber;};

3. The following is the definition of the member function of the graph class (first implementing the member function on the storage of the graph):

graph::graph () {cout<<"Please enter the number of nodes:"; CIN>>Vnumber; Pvnode=NewVnode[vnumber]; Creating a vertex array from new for(inti =0; i < Vnumber; i++)//Enter the information for the diagram through a for loop {cout<<Endl; cout<<"Please enter a node:"; CIN>>Pvnode[i].nodename; stringcheck; Enter the adjacency point of a vertex with "#" as the end flag of the input while(1) {cout<<"Please enter the node's neighboring nodes:"; CIN>>check; if(Check = ="#") { Break; } If the input "#" jumps out of the input loop node*temp =Newnode; If not, allocate node memory, perfect related information temp->nodename =check; cout<<"Enter the ordinal and weighted values of the neighboring nodes:"; CIN>> Temp->nodeindex >> temp->weight; Temp->next =Pvnode[i].next; and place the newly entered node in the appropriate list Pvnode[i].next=temp; }}}graph::~Graph ()//releases the memory used by the linked list, and then releases the memory used by the array {node*currentnode =NULL; Release the memory node that the list occupies*temp =NULL;  for(inti =0; i < Vnumber; i++) {CurrentNode=Pvnode[i].next;  while(CurrentNode! =NULL) {Temp= currentnode->Next; Saves the memory of the next node of the current nodeDeleteCurrentNode; Frees the current node's memory CurrentNode=temp; The next node as the current node}}Delete[]pvnode; Free memory consumed by array}

Second, the graph of the traversal

1. Depth-First traversal

Depth-first traversal through recursive algorithm implementation

The following is the implementation of the member function that implements the depth-first traversal of the diagram:

BOOLGraph::D Eepfirstsearch (intNodeindex) {    if(Nodeindex <0|| Nodeindex >=vnumber)//Determine if the specified starting node is valid {cout<<"The Nodeindex does not exist."; return false; }    if(pvnode[nodeindex].visted = =false)//To determine if the current node has been accessed, and if not, continue {cout<< Pvnode[nodeindex].nodename <<" "; The name of the output node pvnode[nodeindex].visted=true; Modify access Record node*currentnode=Pvnode[nodeindex].next; Find a node adjacent to the current node while(CurrentNode! =NULL) {Deepfirstsearch (CurrentNode-Nodeindex); Continue the above operation by recursion CurrentNode= currentnode->Next; Another adjacent node of the current node try}}return true;}

2. Breadth-First traversal

The breadth-first traversal requires the use of a queue for this data structure.

Code implementation:

BOOLGraph::widefirstsearch (intNodeindex) {    if(Nodeindex <0|| Nodeindex >=vnumber)//Determine if the input node index is valid {cout<<"The Nodeindex does not exist."; return false; } Queue<int>Queue (Vnumber); cout<<"the traversal result of breadth-first search is:"; cout<< Pvnode[nodeindex].nodename <<" "; Print the name of the starting node pvnode[nodeindex].visted=true; Change the access record queue for the starting node.                           EnQueue (Nodeindex); Start node into queueinttemp=0; Node*currentnode =NULL;  while(Queue. Queueempty () = =false)//For each queued node, {queue.        DeQueue (temp); CurrentNode=Pvnode[temp].next; Access all adjacent nodes in the queued order while(currentnode!=NULL) {            if(pvnode[currentnode->nodeindex].visted = =false) {cout<< Currentnode->nodename <<" "; Pvnode[currentnode->nodeindex].visted =true; The node changed access records that have been accessed are merged into the team queue. EnQueue (CurrentNode-Nodeindex); } CurrentNode= currentnode->Next; }} cout<<Endl; return true;}

3, because both of these algorithms need to modify the access record of the node, so each time with one of these two algorithms to implement the traversal needs to initialize the access record to continue to use.

The function code implementation that initializes the access record is:

void graph::clearvisited () {    for (int0; i < vnumber; i++)    {         false ;    }}


Note: The complete code is assigned below, plus a complete code to implement the queue

Http://files.cnblogs.com/files/Rcchio/Graph.rar

Depth-first traversal and breadth-first traversal of graphs with adjacency tables as storage structures (C + +)

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.