邻接表实现图的深度遍历,纠结的问题啊。。。。。
View Code
#include <stdio.h>
#include <malloc.h>
#define MAX 100
typedef struct arcnode/*表节点*/
{
int adjvex; /*邻接点*/
struct arcnode *nextarc;/*指向下一条弧的指针*/
}arcnode;
typedef struct vnode /*头结点*/
{
int data; /*定点信息*/
arcnode * firstarc; /*指向第一个依附该顶点的弧的指针*/
}vnode, adjlist[MAX];
typedef struct /*图*/
{
adjlist vertices; /*顶*/
int vexnum, arcnum; /*图的顶点数和弧数*/
}algraph;
int visited[MAX];
int n = 1;
int locateVex(algraph * g, int v) /*寻找节点V的位置*/
{
int k, n;
for(k = 1; k <= g->vexnum; k++)
{
if(g->vertices[k].data == v)
{
n = k;
break;
}
}
return 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 Print_algraph(algraph * g) /*打印邻接表*/
{
int i;
arcnode *a3;
for(i = 1; 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 Init_algraph(algraph * g) /*初始化图并建图*/
{
int v, v1, v2, i, j;
scanf("%d %d",&g->vexnum, &g->arcnum);//输入(点,边)
for(v = 1; v <= g->vexnum; v++)
{
scanf("%d", &g->vertices[v].data);//输入点 V
g->vertices[v].firstarc = NULL;
}
for(v = 1; v <= g->arcnum; v++)
{
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);
}
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 DFSvisit(algraph *g)//深度优先遍历点顺序
{
int v;
printf("\nDepth_first search:\n");
for(v = 1; v <= g->vexnum; v++)
visited[v] = 0;
for(v = 1; v <= g->vexnum; v++)
if(!visited[v])
DFS(g,v);
}
int main()
{
algraph g;
Init_algraph(&g);
DFSvisit(&g);
return 0;
}