以邻接矩阵作为存储结构,创建4 5 A B C D A B 500 A C 200 A D 150 B C 400 C D 600 无向网,并利用C语言输出该图的所有顶点和邻接矩阵。
时间: 2024-05-09 12:15:16 浏览: 72
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct {
int vertex[MAX_VERTEX_NUM];
int matrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vertex_num, edge_num;
} Graph;
void initGraph(Graph *G) {
int i, j;
G->vertex_num = 0;
G->edge_num = 0;
for (i = 0; i < MAX_VERTEX_NUM; i++) {
G->vertex[i] = 0;
for (j = 0; j < MAX_VERTEX_NUM; j++) {
G->matrix[i][j] = 0;
}
}
}
void addVertex(Graph *G, int v) {
G->vertex[G->vertex_num++] = v;
}
void addEdge(Graph *G, int v1, int v2, int w) {
int i, j;
for (i = 0; i < G->vertex_num; i++) {
if (G->vertex[i] == v1) {
break;
}
}
for (j = 0; j < G->vertex_num; j++) {
if (G->vertex[j] == v2) {
break;
}
}
G->matrix[i][j] = w;
G->matrix[j][i] = w;
G->edge_num++;
}
void printGraph(Graph G) {
int i, j;
printf("Vertex:");
for (i = 0; i < G.vertex_num; i++) {
printf(" %c", G.vertex[i]);
}
printf("\n");
printf("Matrix:\n");
for (i = 0; i < G.vertex_num; i++) {
for (j = 0; j < G.vertex_num; j++) {
printf("%d ", G.matrix[i][j]);
}
printf("\n");
}
}
int main() {
Graph G;
initGraph(&G);
addVertex(&G, 'A');
addVertex(&G, 'B');
addVertex(&G, 'C');
addVertex(&G, 'D');
addEdge(&G, 'A', 'B', 500);
addEdge(&G, 'A', 'C', 200);
addEdge(&G, 'A', 'D', 150);
addEdge(&G, 'B', 'C', 400);
addEdge(&G, 'C', 'D', 600);
printGraph(G);
return 0;
}
```
运行结果:
```
Vertex: A B C D
Matrix:
0 500 200 150
500 0 400 0
200 400 0 600
150 0 600 0
```
阅读全文