(1)DFS
图采用邻接表的结构,头文件algraph.h如下:
#define MAX_VERTEX_NUM 20

typedef int InfoType;
typedef char VertexType;


typedef enum ...{DG, DN, UDG, UDN} GraphKind;


typedef struct ArcNode...{
int adjvex;
struct ArcNode *next;
InfoType info;
}ArcNode;


typedef struct VNode...{
VertexType data;
ArcNode *firstarc;
}VNode, AdjList[MAX_VERTEX_NUM];


typedef struct ...{
AdjList vertex;
int vexnum, arcnum;
GraphKind kind;
}algraph;

bool flag[MAX_VERTEX_NUM];
DFS的递归算法如下:
#include "algraph.h"

#include "stdio.h"
#include "stdlib.h"


void createDN(algraph &g)...{}

void createUDN(algraph &g)...{}

void createUDG(algraph &g)...{}

//get the vertice name's index

int locate(algraph g, char name)...{

for(int i = 0; i < g.vexnum; i++)...{

if(name == g.vertex[i].data)...{
return i;
}
}
return -1;
}


void createDG(algraph &g)...{
printf("input the number of vertex and arcs: ");
scanf("%d %d", &g.vexnum, &g.arcnum);
fflush(stdin);
int i = 0, j = 0, k = 0;
printf("input the name of vertex: ");
//init the vertex names

for(i = 0; i < g.vexnum; i++)...{
scanf("%c", &g.vertex[i].data);
fflush(stdin);
g.vertex[i].firstarc = NULL;
}
//construct the graph's adjacent link list
char v1, v2;
int w;
ArcNode *p;

printf("input the %d arcs v1 v2 and weight: ", g.arcnum);

for(k = 0; k < g.arcnum; k++)...{
scanf("%c %c %d", &v1, &v2, &w);
fflush(stdin);
i = locate(g, v1);
j = locate(g, v2);

//new a link node
p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = j;
p->info = w;
p->next = NULL;

//insert the new node to the head of list

if(!g.vertex[i].firstarc)...{
g.vertex[i].firstarc = p;

}else...{
p->next = g.vertex[i].firstarc;
g.vertex[i].firstarc = p;
}
}
}

//print the graph

void printGraph(algraph g)...{

for(int i = 0; i < g.vexnum; i++)...{
printf("the edges of vretice %c: ", g.vertex[i].data);
ArcNode *p = g.vertex[i].firstarc;

while(p)...{
printf("%c(%d) ", g.vertex[p->adjvex].data, p->info);
p = p->next;
}
printf(" ");
}
}


void createGragh(algraph &g)...{
printf("please input the type of graph: ");
scanf("%d", &g.kind);

switch(g.kind)...{
case DG:
createDG(g);
printGraph(g);
break;
case DN:
createDN(g);
break;
case UDG:
createUDG(g);
break;
case UDN:
createUDN(g);
break;
}
}


void visit(algraph g, int v)...{
printf("%c", g.vertex[v].data);
}

//dfs the graph

void dfs(algraph g, int i, void (* f)(algraph, int))...{
flag[i] = 1;
f(g, i);
ArcNode *p = g.vertex[i].firstarc;

while(p)...{
int adj = p->adjvex;

if(!flag[adj])...{
dfs(g, adj, f);
}
p = p->next;
}
}


void dfsTraval(algraph g, void (* f)(algraph, int))...{

for(int i = 0; i < g.vexnum; i++)...{
flag[i] = 0;
}


for(i = 0; i < g.vexnum; i++)...{

if(!flag[i])...{
dfs(g, i, f);
}
}
}


void main()...{
algraph g;
createGragh(g);

void (* f)(algraph, int);
f = visit;
dfsTraval(g, f);
}

(2)BFS
使用队列对图节点进行遍历。
程序略。
关于图的遍历算法的复杂度:
1. 图的DFS:使用的是邻接表的结构时,算法的复杂度是O(n + e);使用的是邻接矩阵的结构时,算法的复杂度是O(n2)。
2. 遍历图的过程实质是通过边或者弧找邻接点的过程,所以BDS和DFS的算法的复杂度相同,二者的区别在于对顶点的访问顺序不同。