采用的二级指针
#include <stdio.h>
#include <malloc.h>
#define inf -1
typedef struct Graph {
// 顶点个数
int vertices;
int** edges;
}Graph;
//创建图
void GraphCreate(Graph *g,int vertices){
g->vertices=vertices;
// 申请多少个int*的内存
g->edges=(Graph*)malloc(sizeof (int*)*vertices);
// 初始化所有数
for (int i = 0; i < vertices; ++i) {
g->edges[i]=(int*)malloc(sizeof(int)*vertices);
for (int j = 0; j < vertices; ++j) {
g->edges[i][j]=inf;
}
}
}
//毁坏树
void GraphDestroy(Graph* g){
for (int i = 0; i < g->vertices; ++i) {
free(g->edges[i]);
}
free(g->edges);
g->edges=NULL;
}
//新增加一个边
void GraphAddEdge(Graph *g,int u,int v,int w){
g->edges[u][v]=w;
}
//打印图
void GraphPrint(Graph *g){
for (int i = 0; i < g->vertices; ++i) {
for (int j = 0; j < g->vertices; ++j) {
printf("%d ",g->edges[i][j]);
}
printf("\n");
}
}
int main() {
Graph g;
GraphCreate(&g,5);
// GraphAddEdge(&g,0,0,10);
GraphAddEdge(&g,0,1,5);
GraphAddEdge(&g,0,3,8);
GraphAddEdge(&g,1,0,7);
GraphAddEdge(&g,1,2,5);
GraphAddEdge(&g,1,4,12);
GraphAddEdge(&g,2,1,10);
GraphAddEdge(&g,2,3,22);
GraphAddEdge(&g,2,4,20);
GraphAddEdge(&g,3,4,70);
GraphAddEdge(&g,4,3,80);
// 打印数组
GraphPrint(&g);
return 0;
}