“基于邻接矩阵建立图:请输入图的顶点个数和弧数:4 3 请用一行输入图的各个顶点,不用逗号隔开:abcd 请用一行输入图中所有两顶点之间的弧,例如a,b b,c b,d↵ 打印出用邻接矩阵创建的无向图 0 1 0 0 1 0 1 1 0 1 0 0 0 1 0 0 ”。用c语言实现的完整代码
时间: 2024-01-02 15:02:48 浏览: 61
好的,根据您的要求,我们来实现这个程序。请看下面的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_VERTEX_NUM 100 // 最多顶点数
typedef struct {
char vertex[MAX_VERTEX_NUM]; // 存放顶点
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 存放邻接矩阵
int vertex_num; // 实际顶点数
int edge_num; // 实际弧数
} Graph;
void createGraph(Graph* graph);
void printGraph(Graph graph);
int main() {
Graph graph;
createGraph(&graph);
printGraph(graph);
return 0;
}
void createGraph(Graph* graph) {
printf("请输入图的顶点个数和弧数:");
scanf("%d %d", &graph->vertex_num, &graph->edge_num);
getchar(); // 吸收换行符
printf("请用一行输入图的各个顶点,不用逗号隔开:");
for (int i = 0; i < graph->vertex_num; i++) {
scanf("%c", &graph->vertex[i]);
getchar(); // 吸收换行符
}
// 初始化邻接矩阵
for (int i = 0; i < graph->vertex_num; i++) {
for (int j = 0; j < graph->vertex_num; j++) {
graph->edge[i][j] = 0;
}
}
printf("请用一行输入图中所有两顶点之间的弧,例如a,b b,c b,d:\n");
char str[100];
fgets(str, 100, stdin);
char* p = strtok(str, " ");
while (p != NULL) {
int index1 = -1, index2 = -1;
for (int i = 0; i < graph->vertex_num; i++) {
if (graph->vertex[i] == p[0]) {
index1 = i;
}
if (graph->vertex[i] == p[2]) {
index2 = i;
}
}
if (index1 != -1 && index2 != -1) {
graph->edge[index1][index2] = 1;
graph->edge[index2][index1] = 1;
}
p = strtok(NULL, " ");
}
}
void printGraph(Graph graph) {
printf("用邻接矩阵创建的无向图为:\n");
// 打印顶点
printf(" ");
for (int i = 0; i < graph.vertex_num; i++) {
printf("%c ", graph.vertex[i]);
}
printf("\n");
// 打印邻接矩阵
for (int i = 0; i < graph.vertex_num; i++) {
printf("%c ", graph.vertex[i]);
for (int j = 0; j < graph.vertex_num; j++) {
printf("%d ", graph.edge[i][j]);
}
printf("\n");
}
}
```
这是一个基于邻接矩阵建立图的C语言程序,您可以尝试运行并输入您的测试用例,如果有问题请随时提出。
阅读全文