具体内容:
采用邻接矩阵形式村出土,进行图的深度优先搜索并输出结果
算法分析
用邻接矩阵存储图首先定义图的邻接矩阵存储结构,其中一维数组vertexs用来表示与顶点有关的信息,二维数组arcs用来表示图中顶点之间的关系。之后要初始化邻接矩阵,初始化顶点个数以及边的个数,输入数据并且添加权值然后输出矩阵。深度优先搜索然后遍历,最后输出搜索遍历后的顺序。深度优先遍历类似于树的先根遍历,是树先根遍历的推广。深度优先遍历是个递归过程,所以这个算法可以用递归实现。从某个结点v出发,进行优先遍历图的算法采用递归的形式说明如下:1设置访问标识数组并初始化标识数组。2若访问过顶点,则该标识设置为1,并输出当前顶点。3若某个顶点没有被访问过,则继续进行遍历此顶点。4继续找下一个邻接点,递归递归进行遍历,直到所有顶点都被访问。
使用c语言,其中设置了以下函数
函数 |
void CreateUDN(GraphType& G) int LocateVex(GraphType G, char v) void printGraph(GraphType G) void DepthFirshSearch(GraphType G, int v) void Dfs(GraphType G) |
程序流程图
代码
#include <stdio.h>
#include<stdlib.h>
#define MAX 9
typedef struct
{
char vertexs[MAX];
int arcs[MAX][MAX];
int vexnum, arcnum;
}GraphType;
int visited[MAX];
void printGraph(GraphType G);
int LocateVex(GraphType G, char v);
void CreateUDN(GraphType& G)
{
G.vexnum = 8; //输入总顶点数和边数
G.arcnum = 9;
G.vertexs[0] = 'v1'; //输入顶点信息
G.vertexs[1] = 'v2';
G.vertexs[2] = 'v3';
G.vertexs[3] = 'v4';
G.vertexs[4] = 'v5';
G.vertexs[5] = 'v6';
G.vertexs[6] = 'v7';
G.vertexs[7] = 'v8';
for (int i = 0; i < G.vexnum; i++) //初始化邻接矩阵为极大值
{
for (int j = 0; j < G.vexnum; j++)
{
G.arcs[i][j] = 0;
}
}
//输入并建立边,由于是无向图,故一条边需要建立两次
int i, j;
i = LocateVex(G, 'v1');
j = LocateVex(G, 'v2');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v1');
j = LocateVex(G, 'v3');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v2');
j = LocateVex(G, 'v4');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v2');
j = LocateVex(G, 'v5');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v5');
j = LocateVex(G, 'v8');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v4');
j = LocateVex(G, 'v8');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v3');
j = LocateVex(G, 'v6');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v3');
j = LocateVex(G, 'v7');
G.arcs[i][j] = G.arcs[j][i] = 1;
i = LocateVex(G, 'v6');
j = LocateVex(G, 'v7');
G.arcs[i][j] = G.arcs[j][i] = 1;
//打印图的邻接矩阵
printGraph(G);
}
//确定顶点在顶点表数组中的下边,并返回
int LocateVex(GraphType G, char v)
{
for (int i = 0; i < G.vexnum; i++)
{
if (G.vertexs[i] == v)
{
return i;
}
}
}
//输出打印
void printGraph(GraphType G)
{
for (int i = 0; i < G.vexnum; i++)
{
printf("v%d :", i + 1);
for (int j = 0; j < G.vexnum; j++)
{
printf("%d ", G.arcs[i][j]);
}
printf("\n");
}
}
void DepthFirshSearch(GraphType G, int v)
{
int vj;
printf("v%d\t", v+1);
visited[v] = 1;
for (vj = 0; vj < MAX; vj++)
{
if (!visited[vj] && G.arcs[v][vj]== 1)
{
DepthFirshSearch(G, vj);
}
}
}
void Dfs(GraphType G)
{
int v;
for (v = 0; v < G.vexnum; v++)
{
visited[v] = 0;
}
for (v = 0; v < G.vexnum; v++)
{
if (!visited[v])
DepthFirshSearch(G, v);
}
}
int main()
{
GraphType G;
CreateUDN(G);
Dfs(G);
}