Depth-first traversal of graphs--data structures made

Source: Internet
Author: User

#include <iostream>#include<malloc.h>#include<queue>using namespacestd;#defineMaxnum 100//defines the maximum number of fixed points for an adjacency matrixintVisited[maxnum];//the visited array is passed to mark whether the vertex has been accessed, 0 means not accessed, and 1 is accessed//adjacency matrix representation structure of graphstypedefstruct{    CharV[maxnum];//vertex information for graphs    intE[maxnum][maxnum];//vertex information for graphs    intVnum;//number of vertices    intENum;//Number of edges} graph;voidDFS (graph *g,inti) {cout<<"Vertex"<<i<<"has been visited"<<Endl; Visited[i]=1;//Mark Vertex i is accessed    if(i==g->vnum) {        return; }     for(intj=1; j<=g->vnum; J + +)    {        if(visited[j]==0&&g->e[i][j]==1) {Visited[j]=1; DFS (G,J);//The following does not need to restore the scene, traverse once can        }    }}voidDFS (Graph *g) {    inti;  for(i=1; i<=g->vnum; i++)//Initializes a visited array, indicating that all vertices have not been accessed at the beginningvisited[i]=0; //Breadth First Search     for(i=1; i<=g->vnum; i++)//Breadth-First search for each vertex    {        if(visited[i]==0)//If the vertex has not been accessed, the breadth-first traversal from the I vertexDFS (g,i); }}voidCreategraph (graph *g)//Create Figure G{cout<<"Please enter the number of vertices vnum:"; CIN>>g->Vnum; cout<<"Please enter the number of edges enum:"; CIN>>g->ENum; inti,j;  for(i=1; i<=g->vnum; i++)//Initial Paint G         for(j=1; j<=g->vnum; J + +) G->e[i][j]=0; //Enter the condition of the edgecout<<"Please enter the head and tail of each edge"<<Endl;  for(intk=1; k<=g->enum; k++)//initializing edges to connect{cin>>i>>J; G->e[i][j]=1; G->e[j][i]=1; }}intMain () {graph*G; G= (graph*)malloc(sizeof(graph));    Creategraph (g);    DFS (g); return 0;}

Follow the previous breadth-first traversal done, pure hand change, the first glimpse of the doorway

Depth-first traversal of graphs--data structures made

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.