试实现邻接矩阵存储图的深度优先遍历。
函数接口定义:
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );
其中MGraph
是邻接矩阵存储的图,定义如下:
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */
函数DFS
应从第V
个顶点出发递归地深度优先遍历图Graph
,遍历时用裁判定义的函数Visit
访问每个顶点。当访问邻接点时,要求按序号递增的顺序。题目保证V
是图中的合法顶点。
邻接矩阵保存的图用一个结构体实现就行了,是否访问过可以用一个全局变量数组实现
创建无向图代码
MGraph CreateGraph()
{
int Nv, Ne;
Vertex V, W;
MGraph Graph = (MGraph)malloc(sizeof(struct GNode));
// 初始化
Graph->Nv = MaxVertexNum;
Graph->Ne = 0;
for (V = 0; V < Graph->Nv; V++)
{
for (W = 0; W < Graph->Nv; W++)
{
Graph->G[V][W] = INFINITY;
}
}
scanf_s("%d %d", &Nv, &Ne);
Graph->Nv = Nv;
Graph->Ne = Ne;
for (int i = 0; i < Nv; i++)
{
scanf_s("%d %d", &V, &W);
Graph->G[V][W] = 1;
Graph->G[W][V] = 1;
}
return Graph;
}
深搜代码
void DFS(MGraph Graph, Vertex V, void(*Visit)(Vertex))
{
Visit(V);
Visited[V] = true;
for (int i = 0; i < Graph->Nv; i++)
{
if (Graph->G[V][i] != INFINITY && !Visited[i])
{
DFS(Graph, i, Visit);
}
}
}
完整程序
#include <stdio.h>
#include <stdlib.h>
// typedef enum { false, true } bool;
#define MaxVertexNum 10 /* 最大顶点数设为10 */
#define INFINITY 65535 /* ∞设为双字节无符号整数的最大值65535*/
typedef int Vertex; /* 用顶点下标表示顶点,为整型 */
typedef int WeightType; /* 边的权值设为整型 */
typedef struct GNode *PtrToGNode;
struct GNode
{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */
bool Visited[MaxVertexNum]; /* 顶点的访问标记 */
MGraph CreateGraph();
void Visit(Vertex V)
{
printf(" %d", V);
}
void DFS(MGraph Graph, Vertex V, void(*Visit)(Vertex));
int main()
{
MGraph G;
Vertex V;
G = CreateGraph();
scanf_s("%d", &V);
printf("DFS from %d:", V);
DFS(G, V, Visit);
return 0;
}
/* 你的代码将被嵌在这里 */
MGraph CreateGraph()
{
int Nv, Ne;
Vertex V, W;
MGraph Graph = (MGraph)malloc(sizeof(struct GNode));
// 初始化
Graph->Nv = MaxVertexNum;
Graph->Ne = 0;
for (V = 0; V < Graph->Nv; V++)
{
for (W = 0; W < Graph->Nv; W++)
{
Graph->G[V][W] = INFINITY;
}
}
scanf_s("%d %d", &Nv, &Ne);
Graph->Nv = Nv;
Graph->Ne = Ne;
for (int i = 0; i < Nv; i++)
{
scanf_s("%d %d", &V, &W);
Graph->G[V][W] = 1;
Graph->G[W][V] = 1;
}
return Graph;
}
void DFS(MGraph Graph, Vertex V, void(*Visit)(Vertex))
{
Visit(V);
Visited[V] = true;
for (int i = 0; i < Graph->Nv; i++)
{
if (Graph->G[V][i] != INFINITY && !Visited[i])
{
DFS(Graph, i, Visit);
}
}
}