哎。。。这个代码一直在小问题上困扰了很久一直没有查出来,改了很久,郁闷了很久。发篇博客记录一下吧。
深度优先搜索类似于树的先序遍历(先根遍历),也算是其的一种推广。假设初始状态是图中所有顶点未曾被访问,则深度优先搜索可以从图中的某个顶点出发,访问此顶点,然后依次从此顶点未曾被访问的邻接点出发深度优先遍历图,直至图中所有和此顶点有路径相同的顶点都被访问到。若此时图中尚有顶点未被访问到,则另选图中一个未曾访问的顶点做起始点,重复上述过程直到图中所有顶点都被访问到为止。
下面以此图为例进行遍历:
一共8个顶点7条边,遍历的结果如下:
当然了由于是选择的节点顺序不同因此访问的结果也就不同,具体的依据邻接表的存储顺序、遍历的先后等因素来决定。
书上对于这个问题给出了相应的算法模板如下:
具体实现的代码我也分享出来:
Adj_list.h
#ifndef __ADJ_LIST_H__
#define __ADJ_LIST_H__
#define MAX_VERTEX_NUM 20
typedef struct ArcNode
{
char adjvex;
struct ArcNode *nextarc;
int *info;
}ArcNode;
typedef struct VNode
{
char data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct ALGraph
{
AdjList vertices;
int vexnum,arcnum;
int kind;
}ALGraph;
void DFS_visit(ALGraph *G);
void DFS(ALGraph *G,int i);
#endif /* __ADJ_LIST_H__*/
visit_graph.c
/*
************************************************
*Name : visit_graph.c *
*Date : 2015-05-28 *
*Author : sniper *
*Aim : The adjacency list storage the graph and*
* visit the graph. *
************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include "Adj_list.h"
int visit[MAX_VERTEX_NUM]={0};
ALGraph* create(ALGraph *G)
{
int i,j;
int node_pair1,node_pair2;
ArcNode *arc;
node_pair1=0;
node_pair2=0;
i=0;
j=0;
printf("please input the number of node and edge: ");
scanf("%d %d",&G->vexnum,&G->arcnum);
for(i=0;i<G->vexnum;i++)
{
G->vertices[i].data = 'A'+i;
G->vertices[i].firstarc=NULL;
/*
*prepare for visiting
*/
visit[i]=0;
}
printf("finish the Node!\n");
for(j=0;j<G->arcnum;j++)
{
printf("please input the node pair: ");
scanf("%d %d",&node_pair1,&node_pair2);
node_pair1-=1;
node_pair2-=1;
/*
*Node pair get match with each other
*and storage into the adjacency list.
*/
arc = (ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex = node_pair2+'A';
arc->nextarc=G->vertices[node_pair1].firstarc;
G->vertices[node_pair1].firstarc=arc;
}
printf("finish the Adjacency List\n");
return G;
}
/*
*DFS visit
*/
void DFS_visit(ALGraph *G)
{
int i=0;
for(;i<G->vexnum;i++)
{
if(!visit[i])
DFS(G,i);
}
}
void DFS(ALGraph *G,int i)
{
ArcNode *arc;
printf("%c -> ",G->vertices[i].data);
visit[i]=1;
arc=G->vertices[i].firstarc;
while(arc)
{
if(!visit[arc->adjvex-'A'])
DFS(G,arc->adjvex-'A');
arc=arc->nextarc;
}
}
int main()
{
ALGraph *G;
int i;
i=0;
G = (ALGraph *)malloc(sizeof(ALGraph));
G = create(G);
printf("print the DFS\n");
DFS_visit(G);
/*
*Print the Adjacency list
*/
printf("\n print Adjacency list\n");
for(i=0;i<G->vexnum;i++)
{
printf("%c -> ",G->vertices[i].data);
while(G->vertices[i].firstarc!=NULL)
{
printf("%c -> ",G->vertices[i].firstarc->adjvex);
G->vertices[i].firstarc=G->vertices[i].firstarc->nextarc;
}
printf("\n");
}
return 0;
}
还有测试用例
8 7
1 2
1 3
2 4
2 5
3 6
3 7
4 8
运行结果如下图:
完整的工程参见我的github