无向图邻接表的深度优先遍历
/*无向图邻接表的深度优先遍历*/
#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTER_NUM 20
typedef struct ArcNode{ /*表节点*/
int adjvex; /*邻接点*/
struct ArcNode *nextarc; /*指向下一条弧的指针*/
}ArcNode;
typedef struct VNode{ /*头结点*/
int data; /*定点信息*/
ArcNode * firstarc; /*指向第一个依附该顶点的弧的指针*/
}VNode,AdjList[MAX_VERTER_NUM];
typedef struct{ /*图*/
AdjList vertices; /*顶*/
int vexnum,arcnum; /*图的顶点数和弧数*/
}ALGraph;
int visited[MAX_VERTER_NUM];
int n=1;
int LocateVex(ALGraph * G,int v) /*寻找节点V的位置*/
{
int k,n;
for(k=0;k<G->vexnum;k++){
if(G->vertices[k].data==v){
n=k;
break;
}
}
return n;
}
void DFS(ALGraph *G,int v)
{
ArcNode *p;
p=G->vertices[v].firstarc;
if(n<G->vexnum){
printf(" V%d -->",G->vertices[v].data);
n++;
}
else{
printf(" V%d\n",G->vertices[v].data);
}
visited[v]=1;
while(p)
{
if(!visited[p->adjvex])
DFS(G,p->adjvex);
p=p->nextarc;
}
}
void DFSVisited(ALGraph * G)
{
int v;
printf("\n深度优先遍历点顺序: \n");
for(v=0;v<G->vexnum;v++)visited[v]=0;
for(v=0;v<G->vexnum;v++)
if(!visited[v])
DFS(G,v);
}
void Print_ALGraph(ALGraph *G) /*打印邻接表*/
{
int i;
ArcNode *a3;
printf("\n打印无向图邻接表:\n");
for(i=0;i<G->vexnum;i++){
printf(" %d V%d |",i,G->vertices[i].data);
if(G->vertices[i].firstarc!=NULL){
a3=G->vertices[i].firstarc;
while(a3)
{
printf(" --> %d ",a3->adjvex);
a3=a3->nextarc;
}
}
printf("\n");
}
}
void Insertadj(ALGraph * G,int i,int j) /*插入邻接点的下标*/
{
ArcNode *a1,*a2;
a1=(ArcNode *)malloc(sizeof(ArcNode));
a1->adjvex=j;a1->nextarc=NULL;
if(G->vertices[i].firstarc==NULL){
G->vertices[i].firstarc=a1;
}
else{
a2=G->vertices[i].firstarc;
while(a2->nextarc)
{
a2=a2->nextarc;
}
a2->nextarc=a1;
}
}
void Init_ALGraph(ALGraph * G) /*初始化图并建图*/
{
int v,v1,v2,i,j,q,p;
printf("input your vexnum and arcnum:\n");
printf("输入(点,边): ");scanf("%d,%d",&G->vexnum,&G->arcnum);
for(v=0;v<G->vexnum;v++){
printf("输入点 V%d:",(v+1));
scanf("%d",&(G->vertices[v].data));
G->vertices[v].firstarc=NULL;
}
for(v=0;v<G->arcnum;v++)
{
printf("输入(点,点): ");scanf("%d,%d",&v1,&v2);
i=LocateVex(G,v1); /*v1的位置*/
j=LocateVex(G,v2); /*v2的位置*/
Insertadj(G,i,j);
Insertadj(G,j,i);
}
Print_ALGraph(G);
}
int main(int argc,char **argv)
{
ALGraph G;
Init_ALGraph(&G);
DFSVisited(&G);
return 0;
}