邻接矩阵(c语言)

试在邻接矩阵存储结构上实现图的基本操作 matrix_insert_vertex 和matrix_insert_arc,相关定义如下:

typedef int VertexType;

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);
bool matrix_insert_arc(MatrixGraph *G, VertexType v, VertexType w);

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

bool matrix_insert_vertex(MatrixGraph* G, VertexType v)
{
    if (matrix_locate_vertex(G, v) != -1 || G->vexnum + 1 >= MAX_VERTEX_NUM)
        return false;
    G->vertex[G->vexnum] = v;
    G->vexnum++;
    for (int i = 0; i < G->vexnum; i++)
        G->arcs[i][G->vexnum - 1] = 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] = G->arcs[W][V] = 1;
    }
    G->arcnum++;
    return true;
}
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值