数据结构复习代码——图的邻接矩阵表示法实现

1、图的邻接矩阵表示法实现

#include<stdio.h>
#include<malloc.h>
#include<assert.h>

#define Default_Vertex_Size 10

#define T char

//图的定义
typedef struct GraphMtx
{
    int MaxVertices;
    int NumVertices;
    int NumEdge;

    T *VerticesList;
    int **Edge;
}GraphMtx;
//矩阵的初始化
void InitGraphMtx(GraphMtx *g)
{
    g->MaxVertices = Default_Vertex_Size;
    g->NumVertices = g->NumEdge = 0;

    g->VerticesList = (T*)malloc(sizeof(T)*g->MaxVertices);
    assert(g->VerticesList!=nullptr);

    g->Edge = (int**)malloc(sizeof(int*)*g->MaxVertices);
    assert(g->Edge!=nullptr);
    for(int i=0;i<g->MaxVertices;++i)
    {
        g->Edge[i] = (int*)malloc(sizeof(int)*g->MaxVertices);
    }
    for(int i=0;i<g->MaxVertices;++i)
    {
        for(int j=0;j<g->MaxVertices;++j)
        {
            g->Edge[i][j] = 0;
        }
    }
}
void InsertVertex(GraphMtx *g,T v)
{
    if(g->NumVertices >= g->MaxVertices)
        return;
    g->VerticesList[g->NumVertices++] = v;
}
//输出矩阵
void ShowGraphMtx(GraphMtx *g)
{
    printf("  ");
    for(int i=0;i<g->NumVertices;++i)
    {
        printf("%c ",g->VerticesList[i]);
    }
    printf("\n");
    for(int i=0;i<g->NumVertices;++i)
    {
        printf("%c ",g->VerticesList[i]);
        for(int j=0;j<g->NumVertices;++j)
            printf("%d ",g->Edge[i][j]);
        printf("\n");
    }
    printf("\n");
}

int main()
{
    GraphMtx gm;
    InitGraphMtx(&gm);
    InsertVertex(&gm,'A');
    InsertVertex(&gm,'B');
    InsertVertex(&gm,'C');
    InsertVertex(&gm,'D');
    InsertVertex(&gm,'E');
    //InsertVertex(&gm,'A');
    ShowGraphMtx(&gm);
    return 0;
}

 

posted @ 2022-07-14 17:28  往心。  阅读(126)  评论(0编辑  收藏  举报