数据结构用C语言代码实现:建立顶点集为字符集的无向图的领接矩阵存储并输出,输入时的格式为“输入第一条边(vi,vj)和权值:a b 5””
时间: 2023-06-23 22:10:10 浏览: 98
```c
#include <stdio.h>
#define MAX_VERTEX_NUM 20 //最大顶点数
typedef struct {
char vertex[MAX_VERTEX_NUM]; //顶点集合
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //邻接矩阵
int vertexNum, edgeNum; //顶点数和边数
}Graph;
//初始化图
void initGraph(Graph *G) {
int i, j;
G->vertexNum = 0;
G->edgeNum = 0;
for (i = 0; i < MAX_VERTEX_NUM; i++) {
G->vertex[i] = '\0';
for (j = 0; j < MAX_VERTEX_NUM; j++) {
G->edge[i][j] = 0;
}
}
}
//添加顶点
void addVertex(Graph *G, char v) {
G->vertex[G->vertexNum++] = v;
}
//添加边
void addEdge(Graph *G, int vi, int vj, int w) {
G->edge[vi][vj] = w;
G->edge[vj][vi] = w; //无向图对称
G->edgeNum++;
}
int main() {
Graph G;
initGraph(&G);
int i, j, w;
char v1, v2;
printf("请输入边(vi,vj)和权值,输入-1 -1 -1结束:\n");
while (scanf("%c %c %d", &v1, &v2, &w) == 3) {
getchar(); //读取回车符
if (v1 == '-' && v2 == '-' && w == -1) {
break;
}
//判断顶点是否已存在
for (i = 0; i < G.vertexNum; i++) {
if (G.vertex[i] == v1) {
break;
}
}
if (i == G.vertexNum) {
addVertex(&G, v1);
}
for (i = 0; i < G.vertexNum; i++) {
if (G.vertex[i] == v2) {
break;
}
}
if (i == G.vertexNum) {
addVertex(&G, v2);
}
//添加边
for (i = 0; i < G.vertexNum; i++) {
if (G.vertex[i] == v1) {
break;
}
}
for (j = 0; j < G.vertexNum; j++) {
if (G.vertex[j] == v2) {
break;
}
}
addEdge(&G, i, j, w);
}
//输出邻接矩阵
printf("邻接矩阵为:\n");
printf(" ");
for (i = 0; i < G.vertexNum; i++) {
printf("%c ", G.vertex[i]);
}
printf("\n");
for (i = 0; i < G.vertexNum; i++) {
printf("%c ", G.vertex[i]);
for (j = 0; j < G.vertexNum; j++) {
printf("%d ", G.edge[i][j]);
}
printf("\n");
}
return 0;
}
```
阅读全文