图的存储与遍历
如下图所示,首先按邻接矩阵的方法创建图并输出该图,然后再根据该图的邻接矩阵建立该图的邻接表存储结构,分别利用图的邻接矩阵和邻接表实现图的深度优先搜索(DFS)和广度优先搜索(BFS)。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxVertexNum 20 //最大定点数设为100
#define MAXSIZE 20
#define INF 999 //定义无穷大
/****************图的邻接矩阵定义 *******************/
typedef char VertexType; //定点类型设为字符型
typedef int EdgeType; //边的权值设为字符型
typedef struct
{
VertexType vexs[MaxVertexNum]; //顶点表
EdgeType edges[MaxVertexNum][MaxVertexNum]; //邻接矩阵,即边表
int n; //n为顶点数
int e; //e为边数
}MGraph;
/****************图的邻接表定义 *******************/
typedef struct node //边表结点
{
int adjvex; //邻接点域
EdgeType info; //数据域
struct node *next; //指向下一个邻接点的指针域
} EdgeNode;
typedef struct vnode //顶点表结点
{
VertexType vertex; //顶点域
EdgeNode *firstedge; //边表头指针
}VertexNode;
typedef struct
{
VertexNode AdjList[MaxVertexNum]; //顶点表
int n; //顶点表顶点数
int e; //顶点表边数
}ALGraph;
/****************队列的类型及各种操作 *******************/
typedef int datatype;
typedef struct Queue
{
datatype data[MAXSIZE];
datatype top;
datatype bottom;
}Queue;
//初始化
void InitQueue(Queue * p)
{
p->top = 0;
p->bottom = 0;
}
//入队
void EnQueue(Queue *p,datatype val)
{