代码参照了严蔚敏、吴伟民编写的数据结构(C语言版)。
部分内容参考了这位大佬:
https://blog.youkuaiyun.com/jeffleo/article/details/53326648
所有代码采用C语言编写。讲解请查看注释。
头文件及宏定义
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define INFINITY 0//最大值0,即两个顶点之间没有弧时的权值
#define MAX_VERTEX_NUM 20//最大顶点个数
#define OK 1
#define Fail 0
#define False 0
#define True 1
#define Error 0;
typedef定义数据类型和结构体
typedef int VRType;
typedef int Status;
typedef char InfoType;
typedef char VertexType;
typedef enum{
DG,DN,UDG,UDN}GraphKind;//{有向图,有向网,无向图,无向网}
typedef struct ArcCell{
VRType adj;//VRType是顶点关系类型。对无权图,用1和0表示相邻否;对带权图,则为权值类型
InfoType *info;//该弧相关信息的指针
} ArcCell,AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct{
VertexType vexs[MAX_VERTEX_NUM];//顶点向量
AdjMatrix arcs;//邻接矩阵
int vexnum,arcnum;//图的当前顶点数和弧数
GraphKind kind;//图的种类标志
}MGraph;
LocateVex
Status LocateVex(MGraph G, VertexType u){
//找出顶点u在顶点数组vexs中的次序
int i=0;
for (i=0; i<G.vexnum; i++){
if (G.vexs[i]==u)
return i;
}
return False;
}
CreateGraph
Status CreateGraph(MGraph *G){
//构造无向有权图
int i=0,j=0,k=0,w=0;
printf("请输入图的顶点个数和弧数\n");
fflush(stdin);
scanf("%d",&G->vexnum);
fflush(stdin);
scanf("%d",&G->arcnum);
printf("请输入所有顶点\n");
for(i=0;i<G->vexnum;i++){
fflush(stdin);//清空输入缓存区,否则会将上次输入结束后的回车符当成一个字符存入。下面同理
scanf("%c",&G->vexs[i]);//将所有的顶点读入数组vexs中进行存储
}
for(i=0;i<G->vexnum;i++){
//进行初始化,赋初值
for(j=0;j<G->vexnum;j++) {
G->arcs[i][j].adj=INFINITY;
G->arcs[i][j].info=NULL;