題目描述
輸入
連續T組數據輸入,每組數據第一行給出三個正整數,分別表示地下迷宮的結點數N(1 < N <= 1000)、邊數M(M <=
3000)和起始結點編號S,隨後M行對應M條邊,每行給出一對正整數,表示一條邊相關聯的兩個頂點的編號。
輸出
若可以點亮所有結點的燈,則輸出從S開始並以S結束的序列,序列中相鄰的頂點一定有邊,否則只輸出部分點亮的燈
的結點序列,最後輸出0,表示此迷宮不是連通圖。
訪問頂點時約定以編號小的結點優先的次序訪問,點亮所有可以點亮的燈後,以原路返回的方式回到起點。
示例輸入
1
6 8 1
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5
示例輸出
1 2 3 4 5 6 5 4 3 2 1
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int k;
bool vis[110];
struct node
{
int u,v;
node *next;
}*head[110];
void add(int x,int y) //添加邊
{
node *p;
p=new node;
p->u=x;
p->v=y;
p->next=head[x];
head[x]=p;
}
void BFS(int s)
{
node *p;
p=head[s];
vis[s]=true;
int path[110],cnt=0;
while(p)
{
if(!vis[p->v])
{
path[cnt++]=p->v;
vis[p->v]=true;
p=p->next;
}
else
p=p->next;
}
sort(path,path+cnt); //輸出時要按從小到大的序列輸出
for(int i=0;i<cnt;i++)
printf(" %d",path[i]);
for(int i=0;i<cnt;i++)
BFS(path[i]);
}
int main()
{
int n,m,t,u,v;
scanf("%d",&n);
while(n--)
{
scanf("%d %d %d",&k,&m,&t);
for(int i=0;i<k;i++)
head[i]=NULL;
memset(vis,0,sizeof(vis));
for(int i=0;i<m;i++)
{
scanf("%d %d",&u,&v);
add(u,v);
add(v,u);
}
printf("%d",t);
BFS(t);
printf("\n");
}
return 0;
}