IDE:Visual Studio 2019
声明:为了方便书写代码,用到了C++的引用调用特性和iostream作为输入输出,读者可以使用指针调用和scanf_s/print语句实现相同效果
tips:有疑问可以在下面交流,我会尽量回复的
头文件heads.h
#pragma once
#include "stdio.h"
#include "iostream"
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OVERFLOW -1
using namespace std;
typedef short int Status;
头文件Graph.h
#include "heads.h"
typedef int VRType;//顶点关系类型
typedef int InfoType;//弧相关信息
typedef int VertexType;//顶点信息
enum GraphKind{
DG, DN, UDG, UDN };
//数组表示法
#define INFINITY INT_MAX;
#define MAX_VERTEX_NUM 20
typedef struct ArcCell {
VRType adj;
InfoType* info;
}AreCell, AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct {
VertexType vexs[MAX_VERTEX_NUM];
AdjMatrix arcs;
int vexnum, arcnum;//图当前顶点数和弧数
enum GraphKind Kind;
}MGraph;
//MGraph
//创造邻接矩阵
Status CreateMGraph(MGraph& G);
//邻接表
typedef struct ArcNode {
int adjvex;
struct ArcNode* nextarc;
InfoType* info;
}ArcNode,*Arc;
typedef struct VNode {
VertexType data;
ArcNode* firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
enum GraphKind Kind;
}AlGraph;
//结点在图中的定位
int LocateVex(AlGraph G, VertexType e);
//创建邻接表
Status CreateAlGraph(AlGraph& G);
//删除邻接表
Status DestoryAlGraph(AlGraph& G);
//顶点赋值
Status PutVex(AlGraph& G, int i, VertexType e);
//返回第一个邻接点
int FirstAdjVex(AlGraph G, int v);
//返回下一个邻接点
int NextAdjVex(AlGraph G, int v, int w);
//增加结点
Status InsertVex(AlGraph& G, VertexType e);
//删除结点和依附的弧
Status DeleteVex(AlGraph& G, VertexType e);
//插入弧
Status InsertArc(AlGraph& G, int v, int w, InfoType e);
//删除弧
Status DeleteArc(AlGraph& G, int v, int w);
//深度优先遍历
Status visit(AlGraph G, int v);
void DFS(AlGraph G, int v);
void DFSTraverse(AlGraph G, Status(*visit)(AlGraph G, int v));
源文件ALGraph.cpp
#include "Graph.h"
bool visited[MAX_VERTEX_NUM];
Status(*VisitFunc)(AlGraph G, int v);
//弧的初始化
Status InitArc(AlGraph &G,int a,int b,InfoType e) {
Arc q=G.vertices[a].firstarc;
Arc p = (Arc)malloc(sizeof(ArcNode));
p->info = (InfoType*)malloc(sizeof(InfoType));
if (!p