最近复习到了数据结构中的图这一章,随手整理了些图的创建与遍历的完整代码,如下所示:
#include
using namespace std;
#define maxSize 100
typedef struct
{
int no; //顶点编号
char info; //顶点其他信息
}VertexType;
typedef struct
{
int edges[maxSize][maxSize];
int n,e;
VertexType vex[maxSize];
}MGraph;//图的邻接矩阵
typedef struct ArcNode//结点信息
{
int adjvex;
struct ArcNode *nextarc;
int info;
}ArcNode;
typedef struct VNode//头结点或链表信息
{
char data;
ArcNode *firstarc;
}VNode;
typedef struct
{
VNode adjlist[maxSize];//邻接表
int n,e;//顶点数,边数
}AGraph;//图的邻接表
//基本变量
int visit[maxSize] = {0};
void DFS(AGraph *G,int v);//深度优先搜索
void BFS(AGraph *G,int v);//广度优先搜索
int createGraph(AGraph &graph);//创建图
int getIndex(AGraph graph,int data);//由结点值得到索引
void main()
{
AGraph graph;
int ret = createGraph(graph);
if(ret==1)
{
/*cout<<"深度优先搜索"<>graph.n>>graph.e;
cout<<"请输入所有顶点信息"<>graph.adjlist[i].data;//为什么此处不用申请内存空间,声明时已对数组初始化。
graph.adjlist[i].firstarc = NULL;
}
cout<<"请输入"<>first>>second;
int m = getIndex(graph,first);
int n = getIndex(graph,second);
if(m==-1||n==-1)
return -1;
//插入mn
ArcNode *node = new ArcNode;
node->adjvex = n;
//表头插入法
node->nextarc = graph.adjlist[m].firstarc;
graph.adjlist[m].firstarc = node;
//插入nm
ArcNode *node1 = new ArcNode;
node1->adjvex = m;
//表头插入法
node1->nextarc = graph.adjlist[n].firstarc;
graph.adjlist[n].firstarc = node1;
}
return 1;
}
void DFS(AGraph *G,int v)
{
ArcNode *p;
visit[v] = 1;
cout<adjlist[v].data<<' ';
p = G->adjlist[v].firstarc;
while(p!=NULL)
{
if(visit[p->adjvex]==0)
{
DFS(G,p->adjvex);
}
p = p->nextarc;
}
}
void BFS(AGraph *G,int v)
{
ArcNode *p;
int que[maxSize],front=0,rear=0;//定义队列
int j;
cout<adjlist[v].data<<" ";
visit[v] = 1;
rear = (rear+1)%maxSize;//当前结点进队列
que[rear] = v;
while(rear!=front)
{
front = (front+1)%maxSize;//顶点出队
j = que[front];
p = G->adjlist[j].firstarc;
while(p!=NULL)
{
if(visit[p->adjvex]==0)
{
cout<adjlist[p->adjvex].data<<" ";
visit[p->adjvex] = 1;
rear = (rear+1)%maxSize;
que[rear] = p->adjvex;
}
p = p->nextarc;
}
}
}