1、題目:
Problem Description
Input
每組數組分別佔一行。
Output
Sample Input
8 9 1 2 1 3 2 4 2 5 3 6 3 7 4 5 4 8 6 7
Sample Output
1 2 4 5 8 3 6 7 1 2 3 4 5 6 7 8
Author
2、參考代碼:
#include <iostream>
#include <string.h>
using namespace std;
class MGraph{
private:
int vertexNum,arcNum;
int edge[111][111];
int vertex[111];
public:
int vis[111];
MGraph(int* a,int n,int m);
~MGraph(){}
void DFS(int v);
void BFS(int v);
};
MGraph::MGraph(int* a,int n,int m){
vertexNum=n;
arcNum=m;
int i,j;
for(i=1;i<=n;i++)
vertex[i]=a[i];
memset(edge,0,sizeof(edge));
while(m--){
cin>>i>>j;
edge[i][j]=edge[j][i]=1;
}
}
void MGraph::DFS(int v){
cout<<vertex[v]<<" ";
vis[v]=1;
for(int j=0;j<=vertexNum;j++){
if(edge[v][j]==1 && !vis[j])
DFS(j);
}
}
void MGraph::BFS(int v){
int front,rear;
front=rear=-1;
vis[v]=1;
cout<<vertex[v]<<" ";
int Q[111];
Q[++rear]=v;
while(front!=rear){
v=Q[++front];
for(int j=0;j<=vertexNum;j++){
if(edge[v][j]==1 && !vis[j]){
cout<<vertex[j]<<" ";
vis[j]=1;
Q[++rear]=j;
}
}
}
}
int main()
{
int n,m,i,a[111];
while(cin>>n>>m){
for(i=1;i<=n;i++)
a[i]=i;
MGraph w(a,n,m);
memset(w.vis,0,sizeof(w.vis)); ///記得每次開始搜索前都要清空標記
w.DFS(1);
cout<<endl;
memset(w.vis,0,sizeof(w.vis)); ///記得每次開始搜索前都要清空標記
w.BFS(1);
cout<<endl;
}
return 0;
}