数据结构之图 Data Structure — graph

本文介绍了图数据结构的两种表示方式——邻接矩阵和邻接表,并提供了C语言实现。此外,还探讨了最小生成树问题,通过Prim算法展示了C++的代码实现。
摘要由CSDN通过智能技术生成

Adjacency Matrix用C实现如下:

#include<stdio.h>
#include<stdlib.h>
#include<curses.h>

typedef char VertexType;
typedef int EdgeType;

#define MAXVEX 100
#define INFINITY 11111
//#define DEBUG

typedef struct
{
    VertexType vexs[MAXVEX];
    EdgeType arc[MAXVEX][MAXVEX];
    int numVertexes, numEdges; //定义顶点数,边数
}Graph;

//Locate the vertex you need
int locates(Graph *g,char ch)
{
    int i=0;
    for(i=0; i<g->numVertexes;i++){
        if(g->vexs[i]==ch)
            break;
    }

    if(i>=g->numVertexes)  //如果超过顶点数量了,返回-1
        return -1;

    return i; //return the index of the vertex you are looking
}

//建立一个无方向网图的邻接矩阵表示
void CreateGraph(Graph *g)
{
    int i,j,k,w;
    printf("Input the number of vertex and arc:\n");
    scanf("%d %d", &(g->numVertexes), &(g->numEdges));
    printf("#\n");
#ifdef DEBUG
    printf("The number is %d and %d.\n",g->numVertexes,g->numEdges);
#endif

    printf("The total amount of vertexes is %d. Assign to each.\n",g->numVertexes);

    //assign a value to each vertex
    for(i=0;i<g->numVertexes;i++){
        g->vexs[i]=getchar();
        while(g->vexs[i] == '\n'){
            g->vexs[i]=getchar();
        }
    }

#ifdef DEBUG
    for(i=0;i<g->numVertexes;i++){
        printf("Vexs[i] is %c ",g->vexs[i]);
    }
    printf("\n");
#endif

    //initialize each arc/edge as infinity
    for(i=0;i<g->numEdges;i++){
        for(j=0;j<g->numEdges;j++){
            g->arc[i][j]=INFINITY; //initialize
        }
    }

    for (int i = 0; i < g->numEdges; ++i){
        char p,q;
        printf("input the i and j of (Vi,Vj), and the weight:\n"); //一条边的两个结点,和这条边的权重
        p=getchar();
        while(p=='\n'){
            p=getchar();
        }
        q=getchar();
        while(q=='\n'){
            q=getchar();
        }
        scanf("%d",&w);

        int m=-1;
        int n=-1;
        m=locates(g,p);
        n=locates(g,q);
        if(n==-1 || m==-1){
            fprintf(stderr,"No such vertex\n");
            return;
        }
        g->arc[m][n]=w;
        g->arc[n][m]=g->arc[m][n];
    }
}

void printGraph(Graph g){
    int i,j;
    for(i=0;i<g.numVertexes;i++){
        for(j=0;j<g.numVertexes;j++){
            printf("%d\t",g.arc[i][j] );
        }
        printf(
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值