通过代码实现分别实现有向网和无向网的邻接矩阵存储的创建函数,以及图的深度优先搜索函数。通过以下给出的有向网和无向往进行验证。(顶点的数据为顶点的名称字符数组char name[2]:“G1“,G2“,“G3”…)
时间: 2024-02-06 20:13:00 浏览: 36
好的,我将分别为有向网和无向网提供创建函数和深度优先搜索函数的代码实现。
首先是有向网的创建函数 CreateDN:
```c
#define MAX_VERTEX_NUM 20
#define INFINITY 65535
typedef struct {
char name[2];
int weight;
} ArcCell;
typedef struct {
char vertex[MAX_VERTEX_NUM][2];
ArcCell arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexnum, arcnum;
} MGraph;
int LocateVex(MGraph G, char v[]) {
int i;
for (i = 0; i < G.vexnum; i++)
if (strcmp(G.vertex[i], v) == 0)
return i;
return -1;
}
void CreateDN(MGraph* G) {
int i, j, k, w;
char v1[2], v2[2];
ArcCell* p;
printf("input the number of vertexes and arcs: ");
scanf("%d,%d", &G->vexnum, &G->arcnum);
for (i = 0; i < G->vexnum; i++) {
printf("input the %dth vertex: ", i);
scanf("%s", G->vertex[i]);
}
for (i = 0; i < G->vexnum; i++)
for (j = 0; j < G->vexnum; j++)
G->arc[i][j].weight = INFINITY;
for (k = 0; k < G->arcnum; k++) {
printf("input the %dth arc: ", k);
scanf("%s%s%d", v1, v2, &w);
i = LocateVex(*G, v1);
j = LocateVex(*G, v2);
p = &G->arc[i][j];
p->adjvex = j;
p->weight = w;
}
}
```
然后是无向网的创建函数 CreateUDN:
```c
#define MAX_VERTEX_NUM 20
#define INFINITY 65535
typedef struct {
char name[2];
int weight;
} ArcCell;
typedef struct {
char vertex[MAX_VERTEX_NUM][2];
ArcCell arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexnum, arcnum;
} MGraph;
int LocateVex(MGraph G, char v[]) {
int i;
for (i = 0; i < G.vexnum; i++)
if (strcmp(G.vertex[i], v) == 0)
return i;
return -1;
}
void CreateUDN(MGraph* G) {
int i, j, k, w;
char v1[2], v2[2];
ArcCell* p;
printf("input the number of vertexes and arcs: ");
scanf("%d,%d", &G->vexnum, &G->arcnum);
for (i = 0; i < G->vexnum; i++) {
printf("input the %dth vertex: ", i);
scanf("%s", G->vertex[i]);
}
for (i = 0; i < G->vexnum; i++)
for (j = 0; j < G->vexnum; j++)
G->arc[i][j].weight = INFINITY;
for (k = 0; k < G->arcnum; k++) {
printf("input the %dth arc: ", k);
scanf("%s%s%d", v1, v2, &w);
i = LocateVex(*G, v1);
j = LocateVex(*G, v2);
p = &G->arc[i][j];
p->adjvex = j;
p->weight = w;
p = &G->arc[j][i];
p->adjvex = i;
p->weight = w;
}
}
```
最后是深度优先搜索函数 DFS:
```c
#define MAX_VERTEX_NUM 20
typedef struct {
char name[2];
int weight;
} ArcCell;
typedef struct {
char vertex[MAX_VERTEX_NUM][2];
ArcCell arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexnum, arcnum;
} MGraph;
int visited[MAX_VERTEX_NUM];
void DFS(MGraph G, int v) {
int i, w;
visited[v] = 1;
printf("%s ", G.vertex[v]);
for (i = 0; i < G.vexnum; i++) {
if (G.arc[v][i].weight < INFINITY && !visited[i]) {
w = G.arc[v][i].adjvex;
DFS(G, w);
}
}
}
int main(void) {
MGraph G;
CreateDN(&G); // 或者 CreateUDN(&G);
int i;
for (i = 0; i < G.vexnum; i++)
visited[i] = 0;
for (i = 0; i < G.vexnum; i++)
if (!visited[i])
DFS(G, i);
printf("\n");
return 0;
}
```
其中,visited 数组是用于记录每个顶点是否已经被访问过的,DFS 函数会先将当前顶点标记为已访问并输出其名称,然后遍历所有与该顶点有连边且未被访问的顶点并递归地调用 DFS 函数。最后,在主函数中遍历所有顶点并以未访问过的顶点为起点调用 DFS 函数进行全图遍历。
阅读全文