定义:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/197225eedb9c979523c4fef561b18405.jpeg)
下面我们以无向图来演示一遍:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0426e78f325f5207dc2151ce35e00edd.jpeg)
注意:上图最后输出序列为:abcdef
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define max 20
typedef struct Edge{
char data;
struct Edge * nextEdge;
}EDGE;
typedef struct Vertex{
char data;
EDGE * first;
}VERTEX;
typedef struct {
VERTEX list[max];
int vertex;
int edge;
}AdList;
void init_AdList(AdList * );
void DFS(AdList * ,bool * ,int );
void DFStraverse(AdList * );
int main(){
AdList G;
init_AdList(&G);
DFStraverse(&G);
return 0;
}
void init_AdList(AdList * pG){
int i,j,k;
printf("请输入图的顶点个数:\n");
scanf("%d",&pG->vertex);
printf("请输入图的边数:\n");
scanf("%d",&pG->edge);
for(i=0;i<pG->vertex;++i){
printf("请输入各顶点值:");
setbuf(stdin,NULL);
scanf("%c",&pG->list[i].data);
pG->list[i].first=NULL;
}
for(j=0;j<pG->vertex;++j){
int n;
printf("请输入%c的邻接点的个数:\n",pG->list[j].data);
scanf("%d",&n);
if(n!=0){
for(k=0;k<n;++k){
EDGE * pTail;
if(k==0){
int val;
EDGE * pNew=(EDGE *)malloc(sizeof(EDGE));
printf("请输入其邻接点在邻接表中的位置:\n");
scanf("%d",&val);
pG->list[j].first=pNew;
pNew->data=val;
pNew->nextEdge=NULL;
pTail=pNew;
}
else{
int val;
EDGE * pNew=(EDGE *)malloc(sizeof(EDGE));
printf("请输入其邻接点在邻接表中的位置:\n");
scanf("%d",&val);
pTail->nextEdge=pNew;
pNew->data=val;
pNew->nextEdge=NULL;
pTail=pNew;
}
}
}
}
}
void DFStraverse(AdList * pG){
int i;
bool Visted[max];
for(i=0;i<pG->vertex;++i){
Visted[i]=false;
}
for(i=0;i<pG->vertex;++i){
if(!Visted[i]) {
DFS(pG,Visted,i);
}
}
}
void DFS(AdList * pG,bool * Visted,int n){
Visted[n]=true;
printf("%c",pG->list[n].data);
EDGE * p=pG->list[i].first;
while(p){
if(!Visted[p->data]) DFS(pG,Visted,p->data);
else p=p->nextEdge;
}
}