邻接矩阵
试在邻接矩阵存储结构上实现图的基本操作 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;
}