实验过程:
1. 引用以及相关定义:
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <malloc.h>
#define MAXSIZE 200
#define MAX_VERTEX_NUM 20
#define INFINITY INT_MAX
#define MAX 100
using namespace std;
typedef enum{DG,DN,UDG,UDN}GraphKind;
typedef char InfoType;
typedef char VertexType;
typedef int VRTyp;
typedef int Status;
2. 结构体的建立:
typedef struct ArcNode{ //邻接表
int adjvex; //该弧所指向的顶点的位置
struct ArcNode *nextarc; //只想下一条弧的指针
InfoType *info;//该弧相关信息的指针
}ArcNode;
typedef struct VNode{
VertexType data; //顶点信息
ArcNode *firstarc; //指向第一条依附该顶点的弧的指针
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct{
AdjList vertices;
int vexnum,arcnum;//图的当前顶点数和弧数
int kind; //图的种类标志
}ALGraph;
3. 被调函数的编写:
Status Create(ALGraph&G) //构造一个无向图用邻接表
{
int i,j,k,k1,k2;
char ch1,ch2;
cout<<"输入两个数第一个代表vexnum另一个代表arcnum"<<endl;
scanf("%d%d",&G.vexnum,&G.arcnum);
cout<<"输入的数据"<<G.vexnum<<""<<G.arcnum<<endl;
cout<<"输入权值"<<endl;
for(i=1;i<=G.arcnum;i++)
{
cin>>G.vertices[i].data;
G.vertices[i].firstarc=NULL;
}
for(i=1;i<=G.arcnum;i++)
{
cout<<G.vertices[i].data<<" ";
}
cout<<endl;
fflush(stdin);
for(i=1;i<=G.arcnum;i++)
{
cout<<"输入两个字母第一个作为头,第二个作为尾"<<endl;
scanf("%c %c",&ch1,&ch2); //ch1为你想建立链接表中一行表头 ch2为其中的元素
fflush(stdin);
cout<<"输出值"<<endl;
cout<<ch1<<" "<<ch2<<endl;
for(j=1;j<=G.vexnum;j++)
{
if(G.vertices[j].data==ch1)
{
k1=j;
break;;
}
}
for(j=1;j<=G.vexnum;j++)
if(G.vertices[j].data==ch2)
{
k2=j;
break;
}
ArcNode *s;
s=(ArcNode *)malloc(sizeof(ArcNode));
s->adjvex=k2;
s->nextarc=G.vertices[k1].firstarc;
G.vertices[k1].firstarc=s;
cout<<k2<<""<<s->adjvex<<endl;
}
return 0;
}
int visit[MAXSIZE];
void DFS(ALGraph G,VertexTypex)
{
int k1,i;
for(i=1;i<=G.vexnum;i++)
visit[i]=0;
for(i=1;i<=G.vexnum;i++)
{
if(x==G.vertices[i].data)
k1=i;
}
printf("%c",G.vertices[i].data);
visit[k1]=1;
ArcNode *p;
p=G.vertices[k1].firstarc;
while(p)
{
if(visit[p->adjvex]==0)
DFS(G,G.vertices[p->adjvex].data);
p=p->nextarc;
}
}
void BFS(ALGraph G,VertexTypex)
{
struct
{
ArcNode *Q[MAXSIZE];
int fronts,rear;
}Que;
Que.fronts=Que.rear=0;
int i,k;
for(i=1;i<=G.vexnum;i++)
visit[i]=0;
for(i=1;i<=G.vexnum;i++)
{
if(G.vertices[i].data==x)
{
k=i;
break;
}
}
ArcNode *p;
visit[k]=1;
printf("%c",G.vertices[k].data);
Que.rear=(Que.rear+1)%MAXSIZE;
Que.Q[Que.rear]=G.vertices[k].firstarc;
while(Que.rear!=Que.fronts)
{
Que.fronts=(Que.fronts+1)%MAXSIZE;
p=Que.Q[Que.fronts];
while(p)
{
if(visit[p->adjvex]==0)
{
visit[p->adjvex]=1;
printf("%c",G.vertices[p->adjvex]);
Que.rear=(Que.rear+1)%MAXSIZE;
Que.Q[Que.rear]=G.vertices[p->adjvex].firstarc;
}
p=p->nextarc;
}
}
}
4. 主函数:
int main()
{
int a;
char b;
b='A';
ALGraph G;
cout<<"构建一个无向图"<<endl;
a=Create(G);
cout<<"DFS深度遍历输出结果:"<<endl;
DFS(G,b);
cout<<endl;
cout<<"BFS广度遍历输出结果"<<endl;
BFS(G,b);
}