#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 vertex[i]=a[i];
for(int i=0;i for(int j=0;j arc[i][j]=0;
for(int k=0;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< visited[v]=1;
for(int j=0;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< while(front!=rear)
{
v=Q[++front];
for(int j=0;j if(arc[v][j]==1&&visited[j]==0)//访问未被访问的边
{
cout< visited[j]=1;
Q[++rear]=j;
}
}
};
int main()
{
char A[5]={‘a’,’#’,‘b’,’*’,‘c’};
mgraph P(A,5,7);
cout<<“深度优先遍历:”< P.dfstraverse(0);
cout< cout<<“广度优先遍历:”< P.bfstraverse(0);
cout< return 0;
}

你可能感兴趣的:(图)