C语言数据结构-图-邻接矩阵-试在邻接矩阵存储结构上实现图的基本操作 matrix_insert_vertex 和matrix_insert_arc

邻接矩阵

试在邻接矩阵存储结构上实现图的基本操作 matrix_insert_vertex(插入孤立顶点v) 和matrix_insert_arc(在顶点v和w中创建边),相关定义如下:

//顶点为int
typedef int VertexType;

//图的种类:DG 表示有向图, DN 表示有向网, UDG 表示无向图, UDN 表示无向网
typedef enum{
    DG, UDG
}GraphType;

//图的结构
typedef struct{
    VertexType vertex[MAX_VERTEX_NUM]; //顶点向量
    int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //邻接矩阵
    int vexnum, arcnum;   //图的当前顶点数和弧数
    GraphType type;     //图的种类标志
}MatrixGraph;

int matrix_locate_vertex(MatrixGraph MG, VertexType vex); //返回顶点 v 在vertex数组中的下标,如果v不存在,返回-1
bool matrix_insert_vertex(MatrixGraph G, VertexType v);//插入顶点v
bool matrix_insert_arc(MatrixGraph *G, VertexType v, VertexType w);//在顶点v和w中创建边

当成功插入顶点或边时,函数返回true,否则(如顶点或边已存在、插入边时顶点v或w不存在)返回false。

提供代码

#include <stdio.h>
#include "graph.h" // 请不要删除,否则检查不通过

bool matrix_insert_vertex(MatrixGraph *G, VertexType v){


}

bool matrix_insert_arc(MatrixGraph *G, VertexType v, VertexType w){


}

实例解读

参考答案

#include <stdio.h>
#include "graph.h" // 请不要删除,否则检查不通过

bool matrix_insert_vertex(MatrixGraph* G, VertexType v)
{
    //如果v存在或超出最大顶点数
    if (matrix_locate_vertex(G, v) != -1 || G->vexnum + 1 >= MAX_VERTEX_NUM)
        return false;
    G->vertex[G->vexnum] = v;
    G->vexnum++;
	//邻接矩阵增加v的行列
    for (int i = 0; i < G->vexnum; i++)
	{
		G->arcs[i][G->vexnum - 1] = 0;
		G->arcs[G->vexnum - 1][i] = 0;
	}       
    return true;
}

bool matrix_insert_arc(MatrixGraph* G, VertexType v, VertexType w)
{
    int V = matrix_locate_vertex(G, v);
    int W = matrix_locate_vertex(G, w);
    if (V == -1 || W == -1)
        return false;
	//有向图
    if (G->type == "DG") 
    {
        if (G->arcs[V][W] == 1)
            return false;
        G->arcs[V][W] = 1;
    } 
    else {
	//无向图
        if (G->arcs[V][W] == 1 || G->arcs[W][V] == 1)
            return false;
        G->arcs[V][W] = 1;
	G->arcs[W][V] = 1;
    }
    G->arcnum++;
    return true;
}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值