const int MaxSize = 10;
template<class 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;
int visited[MaxSize];
};
构造
template<class T>
MGraph<T>::MGraph(T a[],int n,int e){
vertexNum = n;
edgeNum = 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++)
edge[i][j] = 0;
int x,y;
for(int i=0; i<vertexNum;i++){
cin>>x>>y;
edge[x][y] = 1;
edge[y][x] = 1;
}
for(int i=0; i<vertexNum; i++)
visited[i] = 0;
}
深度遍历
template<class T>
void MGraph<T>::DFTraverse(int v){
cout<<vertex[v];
visited[v] = 1;
for(int i=0; i<vertexNum; i++)
if(edge[v][i]==1 && visited[i]!=1)
DFTraverse(i);
}
广度遍历
template<class T>
void MGraph<T>::BFTraverse(int v){
int Q[MaxSize], w;
int front = -1, rear = -1;
for(int i=0; i<vertexNum; i++)
visited[i] = 0;
cout<<vertex[v];
visited[v] = 1;
Q[++rear] = v;
while(front != rear){
w = Q[++front];
for(int i=0; i<vertexNum; i++)
if(edge[v][i] == 1 && visited[i] == 0){
cout<<vertex[i];
visited[i] = 1;
Q[++rear] = i;
}
}
}