邻接矩阵的代码C语言
时间: 2024-01-05 07:20:28 浏览: 62
以下是邻接矩阵的代码示例,使用C语言实现:
```c
#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);
// 打印邻接矩阵
printGraph(&graph);
return 0;
}
```
阅读全文