(1)由给定的顶点和边的信息构造图的邻接矩阵存储; (2)对该图进行深度优先搜索,输出搜索得到的结点序列; 以邻接表作存储结构,用克鲁斯卡尔算法构造最小生成树。用c语言编写
时间: 2024-02-19 10:58:36 浏览: 71
好的,让我来回答你的问题。
首先,对于第一个问题,你可以按照以下方式构造邻接矩阵存储:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
#define INFINITY 65535
typedef int VertexType;
typedef int EdgeType;
typedef struct {
VertexType vexs[MAX_VERTEX_NUM];
EdgeType edges[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int n, e;
} MGraph;
void CreateMGraph(MGraph *G)
{
int i, j, k, w;
printf("请输入图的顶点数和边数: ");
scanf("%d %d", &(G->n), &(G->e));
for (i = 0; i < G->n; i++) {
printf("请输入第%d个顶点的值: ", i + 1);
scanf("%d", &(G->vexs[i]));
}
for (i = 0; i < G->n; i++) {
for (j = 0; j < G->n; j++) {
G->edges[i][j] = INFINITY;
}
}
for (k = 0; k < G->e; k++) {
printf("请输入第%d条边的起点下标、终点下标、权值: ", k + 1);
scanf("%d %d %d", &i, &j, &w);
G->edges[i][j] = w;
G->edges[j][i] = w;
}
}
void DFS(MGraph G, int i, int *visited)
{
int j;
visited[i] = 1;
printf("%d ", G.vexs[i]);
for (j = 0; j < G.n; j++) {
if (G.edges[i][j] != INFINITY && !visited[j]) {
DFS(G, j, visited);
}
}
}
void DFSTraverse(MGraph G)
{
int i;
int visited[MAX_VERTEX_NUM];
for (i = 0; i < G.n; i++) {
visited[i] = 0;
}
for (i = 0; i < G.n; i++) {
if (!visited[i]) {
DFS(G, i, visited);
}
}
}
typedef struct {
int from, to;
int weight;
} Edge;
void CreateEdge(Edge *edge, int from, int to, int weight)
{
edge->from = from;
edge->to = to;
edge->weight = weight;
}
void CreateEdges(Edge *edges, int n)
{
int i, from, to, weight;
for (i = 0; i < n; i++) {
printf("请输入第%d条边的起点下标、终点下标、权值: ", i + 1);
scanf("%d %d %d", &from, &to, &weight);
CreateEdge(&edges[i], from, to, weight);
}
}
int cmp(const void *a, const void *b)
{
return ((Edge *)a)->weight - ((Edge *)b)->weight;
}
int Find(int *parent, int f)
{
while (parent[f] > 0) {
f = parent[f];
}
return f;
}
void Kruskal(MGraph G)
{
int i, j, n, m;
int parent[MAX_VERTEX_NUM];
Edge edges[MAX_VERTEX_NUM];
CreateEdges(edges, G.e);
qsort(edges, G.e, sizeof(Edge), cmp);
for (i = 0; i < G.n; i++) {
parent[i] = 0;
}
printf("最小生成树的边为: \n");
for (i = 0; i < G.e; i++) {
n = Find(parent, edges[i].from);
m = Find(parent, edges[i].to);
if (n != m) {
parent[n] = m;
printf("(%d, %d) %d\n", edges[i].from, edges[i].to, edges[i].weight);
}
}
}
int main()
{
MGraph G;
CreateMGraph(&G);
printf("深度优先搜索序列为: ");
DFSTraverse(G);
printf("\n");
Kruskal(G);
return 0;
}
```
以上就是我对你的问题的回答,希望能够帮到你。
阅读全文