#include
using namespace std;
const int maxsize=10;
template
class mgraph
{
public:
mgraph(T a[],int n,int e);
~mgraph(){}
void dfstraverse(int v);
void bfstraverse(int v);
private:
T vertex[maxsize];
int arc[maxsize][maxsize];
int vertexnum,arcnum;
};
template
mgraph::mgraph(T a[],int n,int e)
{
vertexnum=n;arcnum=e;
for(int i=0;i<vertexnum;i++)
vertex[i]=a[i];
for(int i=0;i<vertexnum;i++)
for(int j=0;j<vertexnum;j++)
arc[i][j]=0;
for(int k=0;k<arcnum;k++)
{
int i,j;
cin>>i>>j;
arc[i][j]=1;arc[j][i]=1;
}
};
template
void mgraph::dfstraverse(int v)//深度优先遍历
{
int x;
int visited[maxsize];
cout<<vertex[v];
visited[v]=1;
for(int j=0;j<vertexnum;j++)
if(arc[v][j]==1&&visited[j]==0)
dfstraverse(j);
};
template
void mgraph::bfstraverse(int v)//广度优先遍历
{
int rear;
int front=rear=-1;
int Q[maxsize];
int visited[vertexnum];
cout<<vertex[v];visited[v]=1;Q[++rear]=v;
while(front!=rear)
{
v=Q[++front];
for(int j=0;j<vertexnum;j++)
if(arc[v][j]==1&&visited[j]==0)//访问未被访问的边
{
cout<<vertex[j];
visited[j]=1;
Q[++rear]=j;
}
}
};
int main()
{
char A[5]={‘a’,’#’,‘b’,’*’,‘c’};
mgraph P(A,5,7);
cout<<“深度优先遍历:”<<endl;
P.dfstraverse(0);
cout<<endl;
cout<<“广度优先遍历:”<<endl;
P.bfstraverse(0);
cout<<endl;
return 0;
}