#include<iostream>
#include<cstring>
using namespace std;
struct EdgeNode//定义边表结点
{
int adjvex;//邻结点域
EdgeNode *next;
} ;
template <typename T>
struct VertexNode
{
T vertex;
EdgeNode *firstEdge;
};
const int MaxSize=10;//图中最多顶点个数
template <typename T>
class MGraph
{
public:
MGraph(T a[],int n,int e);//构造函数
~MGraph(){};//析构函数--释放空间
void DFTraverse(int v);//深度优先遍历图
void BFTraverse(int v);//广度优先遍历图
private:
T vertex[MaxSize];//存放图中顶点的数组
int edge[MaxSize][MaxSize];//存放图中边的数组
int vertexNum,edgeNum;//图的顶点数和边数
};
template <typename T>
//构造函数--图的建立
MGraph<T>::MGraph(T a[],int n,int e)
{
int i,j,k;
vertexNum=n;edgeNum=e;
for(i=0;i<vertexNum;i++)//存放顶点
vertex[i]=a[i];
for(i=0;i<vertexNum;i++)
{
for(j=0;j<vertexNum;j++)
{
edge[i][j]=0;
}
}
for(k=0;k<edgeNum;k++)//依次输入每一条边
{
cin>>i>>j;//输入边依附的两个顶点的编号
edge[i][j]=1;edge[j][i]=1;//置有边的标志
}
}
//析构函数为空
int visited[MaxSize];
template <typename T>
//深度优先遍历
void MGraph<T>::DFTraverse(int v)
{
cout<<vertex[v];
visited[v]=1;
for(int j=0;j<vertexNum;j++)
if(edge[v][j]==1&&visited[j]==0) DFTraverse(j);
}
//广度优先遍历
template <typename T>
void MGraph<T>::BFTraverse(int v)
{
int w,j,Q[MaxSize];//采用顺序队列
int front=-1,rear=-1;//初始化队列
cout<<vertex[v];
visited[v]=1;
Q[++rear]=v;
while(front!=rear)//当队列非空时
{
w=Q[++front];//将对头元素出队并送到v中
}
for(j=0;j<vertexNum;j++)
{
if(edge[w][j]==1&&visited[j]==0){
cout<<vertex[j];
visited[j]=1;
Q[++rear]=j;
}
}
}
//把邻接矩阵存储的类定义和各个成员函数定义放到这里
int main()
{
int i;
char ch[]={'A','B','C','D','E'};
MGraph<char> MG;
MG.MGraph(ch[],5,6)//建立具有5个顶点6条边的无向图
for(i=0;i<MaxSize;i++)
{
visited[i]=0;
}
cout<<"深度优先遍历序列为:";
MG.DFTraverse(0);//从顶点0出发进行深度优先遍历
for(i=0;i<MaxSize;i++)
{
visited[i]=0;
}
cout<<"广度优先遍历序列为:";
MG.BFTraverse(0);//顶点0出发进行guang度优先遍历
return 0;
}