邻接矩阵建立图

邻接矩阵建立图

typedef struct gnode * mgraph;
struct gnode
{
    int nv;    //顶点数 
    int ne;    //边数 
    weighttype g[maxnum][maxnum];
    datatype data[maxnum];   //存顶点的数据 
};

typedef int vertex;


//建立没有边的图 
mgraph creategraph(int vertexmax)
{
    vertex v, w;
    mgraph graph;
    
    graph = (mgraph)malloc(sizeof(struct gnode));
    graph->nv = vertexmax;
    graph->ne = 0;
    
    for(v = 0; v < graph->nv; v++)
    {
        for(w = 0; w < graph->nv; w++)
        {
            graph->g[v][w] = 0;   //将矩阵先初始化为0
        }
    }
    return graph;
}


//向图中插入边
typedef struct enode * edge;
struct enode
{
    vertex v1, v2;        //有向边 
    weighttype weight;   //权重 
};

void insertedge(mgraph graph, edge e)
{
    graph->g[e->v1][e->v2] = e->weight;     //为图中相连结点添加权重
    
    graph->g[e->v2][e->v1] = e->weight;
}


mgraph buildgraph()
{
    mgraph graph;
    edge e;
    vertex v;
    int nv, i;
    
    scanf("%d", &nv);
    graph = createmgraph(nv);
    scanf("%d", &(graph->ne));
    
    if(graph->ne != 0)
    {
        e = (edge)malloc(sizeof(struct enode));
        for(i = 0; i < graph->ne; i++)
        { 
            scanf("%d %d %d", &e->v1, &e->v2, &e->weight);
            insertedge(graph, e);
        }
    }
    
    //若顶点有数据,存入数据 
    for(v = 0; v < graph->nv; v++)
    {
        scanf("%c", &graph->data[v]);
    }
    
    return graph;
 } 
 
 
 


  简便方法


 int g[maxn][maxn], nv, ne;
 void buildgraph()
 {
     int i, j, v1, v2, w;
     
     scanf("%d", &nv);
     for(i = 0; i < nv; i++)
     {
        for(j = 0; j < nv; j++)
        {
            g[i][j] = 0;
        }
    }
    
    scanf("%d", &ne);
    for(i = 0; i < ne; i++)
    {
        scanf("%d %d %d", &v1, &v2, &w);
        
        g[v1][v2] = w;
        g[v2][v1] = w;
    }

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值