题目描述
有一个地下迷宫,它的通道都是直的,而通道所有交叉点(包括通道的端点)上都有一盏灯和一个开关;请问如何从某
个起点开始在迷宫中点亮所有的灯并回到起点?
输入
连续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;
}
#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;
}