代码中示例用图:
/*
* 基于邻接矩阵存储的图的深度优先搜索算法(DFS)
*/
#include<stdio.h>
#include<stdlib.h>
//自定义Bool类型
typedef int Bool;
#define FALSE 0
#define TRUE 1
//定义顶点类型
typedef char VertexType;
typedef int EdgeType;
#define MAXVEX 30
typedef struct Graph {
//存储顶点的一位数组
VertexType vertex[MAXVEX];
//存储边信息的邻接矩阵
EdgeType edge[MAXVEX][MAXVEX];
//当前图中的顶点数和边数
int verNum;
int edgeNum;
}Graph;
//顶点访问标志数组
Bool visited[MAXVEX];
//创建图
void createGraph(Graph *G) {
G->verNum = 6;
G->edgeNum = 8;
//建立顶点表
G->vertex[0] = 'A';
G->vertex[1] = 'B';
G->vertex[2] = 'C';
G->vertex[3] = 'D';
G->vertex[4] = 'E';
G->vertex[5] = 'F';
//初始化图
for(int i = 0; i < G->verNum; i++) {
for(int j = 0; j < G->verNum; j++) {
G->edge[i][j] = 0;
}
}
//初始化边信息
G->edge[0][2] = 1;
G->edge[0][4] = 1;
G->edge[1][2] = 1;
G->edge[1][5] = 1;
G->edge[2][0] = 1;
G->edge[2][1] = 1;
G->edge[2][3] = 1;
G->edge[2][5] = 1;
G->edge[3][2] = 1;
G->edge[3][5] = 1;
G->edge[4][0] = 1;
G->edge[4][5] = 1;
G->edge[5][1] = 1;
G->edge[5][2] = 1;
G->edge[5][3] = 1;
G->edge[5][3] = 1;
printf("该图的邻接矩阵为:\n");
for(int i = 0; i < G->verNum; i++) {
for(int j = 0; j < G->verNum; j++) {
printf("%d\t", G->edge[i][j]);
}
printf("\n");
}
}
//邻接矩阵的深度优先递归算法, i为指定开始的搜索顶点
void DFSTraverse(Graph G, int i) {
visited[i] = TRUE;
printf("%c ", G.vertex[i]);
for(int j = 0; j < G.verNum; j++) {
if(G.edge[i][j] == 1 && !visited[j]) {
//对为访问的邻接顶点进行递归调用
DFSTraverse(G, j);
}
}
}
int main(void) {
Graph G;
createGraph(&G);
//初始时所有顶点都是未访问的
for(int i = 0; i < G.verNum; i++) {
visited[i] = FALSE;
}
printf("\n深度遍历:");
DFSTraverse(G, 0);
}