#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