用邻接矩阵创建无向图c语言
时间: 2024-02-25 18:57:52 浏览: 70
邻接矩阵无向图
下面是用邻接矩阵创建无向图的C语言代码示例:
```c
#include <stdio.h>
#define MAX_SIZE 10
int graph[MAX_SIZE][MAX_SIZE];
int num_vertices;
void createGraph()
{
int i, j;
printf("Enter the number of vertices: ");
scanf("%d", &num_vertices);
// Initialize graph to all 0's
for (i = 0; i < num_vertices; i++) {
for (j = 0; j < num_vertices; j++) {
graph[i][j] = 0;
}
}
// Add edges
for (i = 0; i < num_vertices; i++) {
for (j = i+1; j < num_vertices; j++) {
int edge_exists;
printf("Does an edge exist between vertex %d and %d? (1 for yes, 0 for no): ", i+1, j+1);
scanf("%d", &edge_exists);
if (edge_exists) {
graph[i][j] = 1;
graph[j][i] = 1;
}
}
}
}
void printGraph()
{
int i, j;
printf("The adjacency matrix representation of the graph is:\n");
for (i = 0; i < num_vertices; i++) {
for (j = 0; j < num_vertices; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}
}
int main()
{
createGraph();
printGraph();
return 0;
}
```
该代码使用邻接矩阵表示无向图。在 `createGraph()` 函数中,用户被要求输入顶点数和边的信息。然后,使用 `graph` 数组来存储每个顶点之间是否有边。在 `printGraph()` 函数中,打印出 `graph` 数组的内容,以显示图形的邻接矩阵表示。
阅读全文