编写一个算法,完成无向图的邻接矩阵和邻接表的构造函数。在此基础上,完成图的深度优先和广度优先遍历算法。
#include <iostream.h>
typedef char ElemType;
#define MaxSize 10
typedef struct
{
int arc[MaxSize][MaxSize];
int vextexnum,arcnum;
ElemType vertex[MaxSize];
}MGraph;
bool visited[MaxSize];
bool visited1[MaxSize];
typedef struct ArcNode
{
int adjvex;
struct ArcNode *next;
}ArcNode;
typedef struct VertexNode
{
ElemType vertex;
ArcNode *firstedge;
}VertexNode;
typedef struct ALGraph
{
VertexNode adjlist[MaxSize];
int vextexnum,arcnum;
}ALGraph;
void MGraph1(MGraph &g,ElemType a[],int n,int e)
{
g.vextexnum=n;
g.arcnum=e;
int i,j,k;
for(i=0;i<g.vextexnum;i++)
g.vertex[i]=a[i];
for(i=0;i<g.vextexnum;i++)
for(j=0;j<g.vextexnum;j++)
g.arc[i][j]=0;
for(k=0;k<g.arcnum;k++)
{
cin>>i>>j;
g.arc[i][j]=1;
g.arc[j][i]=1;
}
}
void ALGraph1(ALGraph &g,ElemType a[],int n,int e)
{
g.vextexnum=n;
g.arcnum=e;
int i,j,k;
ArcNode *s;
for(i=0;i<g.vextexnum;i++)
{
g.adjlist[i].vertex=a[i];
g.adjlist[i].firstedge=NULL;
}
for(k=0;k<g.arcnum;k++)
{
cin>>i>>j;
s=new ArcNode;
s->adjvex=j;
s->next=g.adjlist[i].firstedge;
g.adjlist[i].firstedge=s;
}
}
void DispMat(MGraph &g)
{
int i,j;
for(i=0;i<g.vextexnum;i++)
cout<<g.vertex[i]<<" ";
cout<<endl;
for(i=0;i<g.vextexnum;i++)
{
for(j=0;j<g.vextexnum;j++)
if(g.arc[i][j]==0)
cout<<"0"<<" ";
else
cout<<g.arc[i][j]<<" ";
cout<<endl;
}
}
void DispAdj(ALGraph &G)
{
int i;
ArcNode *p;
for(i=0;i<G.vextexnum;i++)
{
p=G.adjlist[i].firstedge;
if(p!=NULL)
cout<<i<<" ";
while(p!=NULL)
{
cout<<p->adjvex<<" ";
p=p->next;
}
cout<<endl;
}
}
void DFSraverse(MGraph g,int v)
{
int j;
cout<<g.vertex[v]<<" ";
visited[v]=1;
for(j=0;j<g.vextexnum;j++)
if(g.arc[v][j]==1 && visited[j]==0)
DFSraverse(g,j);
}
void BFSraverse(MGraph g,int v)
{
int j;
int front,rear;
int Q[MaxSize];
front=rear=-1;
cout<<g.vertex[v]<<" ";
visited1[v]=1;
Q[++rear]=v;
while(front!=rear)
{
v=Q[++front];
for(j=0;j<g.vextexnum;j++)
{
if(g.arc[v][j]==1&&visited1[j]==0)
{
cout<<g.vertex[j]<<" ";
visited1[j]=1;
Q[++rear]=j;
}
}
}
}
void main()
{
MGraph g;
ALGraph g1;
ElemType a[]={'a','b','c','d'};
cout<<"请输入邻接矩阵的4条边两端的顶点:"<<endl;
MGraph1(g,a,4,4);
cout<<"图G的邻接矩阵:"<<endl;
DispMat(g);
cout<<endl;
cout<<"请输入邻接表的4条边两端的顶点:"<<endl;
ALGraph1(g1,a,4,4);
cout<<"图G的邻接表:"<<endl;
DispAdj(g1);
cout<<"深度优先:";
DFSraverse(g,0);
cout<<endl;
cout<<"广度优先:";
BFSraverse(g,0);
cout<<endl;
}