https://blog.csdn.net/Achenming1314/article/details/105203878
#include <iostream>
/**
*DFS usage:Refer to the hype data structure
*/
using namespace std;
#define maxvertex 100
typedef char vertextype; //vertex
typedef int Edgetype ; //edge
//define linklist node
typedef struct EdgeNode{
int adjvex ;//adjvex store the index of vertex
Edgetype weight;
struct EdgeNode *next; //list
}EdgeNode;
//define array which can be used to store the vertex
typedef struct VertexNode{
vertextype data;
EdgeNode* firstedge ;//Edge pointer
}VertexNode,Adjlist[maxvertex];
//define grapha which describe the numbers of vertex and edge
typedef struct {
Adjlist adjlist;
int numvertex,numedge;
}GraphAdjlist;
//establish the grapha
void CreateALGrapha(GraphAdjlist *G){
int i,j,k;
EdgeNode *e;
cout<<"input the numbers of vertex and edge:"<< endl;
cin>>G->numvertex>>G->numedge;
cout<<"input the information of vertex"<<endl;
for(i=0;i<G->numvertex;i++){
cin>>G->adjlist[i].data;
G->adjlist[i].firstedge=NULL;
}
for(k=0;k<G->numedge;k++){
//establish
cout<<"input (Vi,Vj) number:"<<endl;
cin>> i>>j;
e=(EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex=j; //index of adjvex
e->next=G->adjlist[i].firstedge;
G->adjlist[i].firstedge=e;
e=(EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex=i;
e->next=G->adjlist[j].firstedge;
G->adjlist[j].firstedge=e;
}
}
typedef int boollean;
boollean visited[maxvertex];
/*Depth recursive algorithm of adjacency list*/
void DFS(GraphAdjlist GL,int i){
EdgeNode *p;
visited[i]=1;
cout<<GL.adjlist[i].data<<" ";
p=GL.adjlist[i].firstedge;
while(p){
if(!visited[p->adjvex]){
DFS(GL,p->adjvex);
}
p=p->next;
}
}
/*print the asjacency list*/
void DFSTraverse(GraphAdjlist GL){
int i;
for(int i=0;i<GL.numvertex;i++){
visited[i]=0;
}
for(i=0;i<GL.numvertex;i++){
if(!visited[i])
DFS(GL,i);
}
}
int main()
{
GraphAdjlist *G=new GraphAdjlist;
CreateALGrapha(G);
DFSTraverse(*G);
return 0;
}