图的数组(邻接矩阵)存储

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

#define MAX_NAME 5 /* The largest length of vertex string + 1 */
#define MAX_INFO 20 /* The largest length of info string + 1 */
#define INFINITY  99999
#define MAX_VERTEX_NUM 20

typedef int VRType;
typedef char InfoType;
typedef char VertexType[MAX_NAME];
typedef enum {DG, DN, UDG, UDN} GraphKind;

typedef struct
{
    VRType adj;
    InfoType* info;
} AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];

typedef struct
{
    VertexType vexs[MAX_VERTEX_NUM];
    AdjMatrix arcs;
    int vexnum, arcnum;
    GraphKind kind;
} MGraph;

int LocateVex(MGraph G, VertexType u)
{  /* 初始条件:图G存在,u和G中顶点有相同特征 */
   /* 操作结果:若G中存在顶点u,则返回该顶点在图中位置;否则返回-1 */
    int i;
    for(i = 0; i < G.vexnum; ++i)
        if(strcmp(u, G.vexs[i]) == 0)
            return i;
    return -1;
}

int Create_UDN(MGraph& G)
{   /* 采用数组(邻接矩阵)表示法,构造无向网G */
    int i, j, k, w, IncInfo;
    char s[MAX_INFO], *info;
    VertexType va, vb;

    printf("Input vexnum, arcnum, whether include info(Y:1, N:0)(separate with comma):\n ");
    scanf("%d,%d,%d", &G.vexnum, &G.arcnum, &IncInfo);

    printf("Input values of %d vertice(< %d chars):\n", G.vexnum, MAX_NAME);
    for(i = 0; i < G.vexnum; ++i) /* construct vertex vector */
        scanf("%s", G.vexs[i]);
    for(i = 0; i < G.vexnum; ++i)
        for(j = 0; j < G.vexnum; ++j)
        {
            G.arcs[i][j].adj = INFINITY;
            G.arcs[i][j].info = NULL;
        }

    printf("Input %d arcs' vertex1, vertex2, weight(separate with space): \n", G.arcnum);
    for(k = 0; k < G.arcnum; ++k)
    {
        scanf("%s%s%d%*c", va, vb, &w);  /* %*c吃掉回车符 */
        i = LocateVex(G, va);
        j = LocateVex(G, vb);
        G.arcs[i][j].adj = G.arcs[j][i].adj = w; /* 无向 */
        if(IncInfo)
        {
            printf("Input related info of this arc(<%d chars): ", MAX_INFO);
            scanf("%s", s);
            w = strlen(s);
            if(w)
            {
                info = (char*)malloc((w + 1) * sizeof(char));
                strcpy(info, s);
                G.arcs[i][j].info = G.arcs[j][i].info = info;  /* 无向 */
            }
        }
    }
    G.kind = UDN;
    return 1;
}

void Display(MGraph G)
{
    int i, j;
    printf("The matrix is:\n ");
    for(i = 0; i < G.vexnum; ++i)
        printf("     %s", G.vexs[i]);
    printf("\n");
    for(i = 0; i < G.vexnum; ++i)
    {
        printf("%s", G.vexs[i]);
        for(j = 0; j < G.vexnum; ++j)
            printf("%6d", G.arcs[i][j].adj);
        printf("\n");
    }
}

int main()
{
    MGraph g;
    Create_UDN(g);
    Display(g);
    return 0;
}


运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值