c语言实现邻接矩阵

采用的二级指针

#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;
}

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值