用c语言实现无向图的邻接矩阵
时间: 2024-01-02 13:22:27 浏览: 86
以下是用C语言实现无向图邻接矩阵的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct _graph {
char vexs[MAX]; // 顶点集合
int vexnum; // 顶点数
int edgnum; // 边数
int matrix[MAX][MAX]; // 邻接矩阵
} Graph, *PGraph;
// 初始化图
void initGraph(PGraph pGraph, int vexnum) {
int i, j;
pGraph->vexnum = vexnum;
pGraph->edgnum = 0;
for (i = 0; i < vexnum; i++) {
for (j = 0; j < vexnum; j++) {
pGraph->matrix[i][j] = 0;
}
}
}
// 添加边
void addEdge(PGraph pGraph, int start, int end) {
pGraph->matrix[start][end] = 1;
pGraph->matrix[end][start] = 1;
pGraph->edgnum++;
}
// 打印邻接矩阵
void printGraph(PGraph pGraph) {
int i, j;
for (i = 0; i < pGraph->vexnum; i++) {
for (j = 0; j < pGraph->vexnum; j++) {
printf("%d ", pGraph->matrix[i][j]);
}
printf("\n");
}
}
int main() {
Graph graph;
int vexnum = 5; // 顶点数
initGraph(&graph, vexnum);
// 添加边
addEdge(&graph, 0, 1);
addEdge(&graph, 0, 2);
addEdge(&graph, 0, 3);
addEdge(&graph, 1, 4);
addEdge(&graph, 2, 3);
addEdge(&graph,3, 4);
// 打印邻接矩阵
printGraph(&graph);
return 0;
}
```
阅读全文