迷宫探索DFS(递归记录来回路径)

Problem Description
有一个地下迷宫,它的通道都是直的,而通道所有交叉点(包括通道的端点)上都有一盏灯和一个开关;请问如何从某个起点开始在迷宫中点亮所有的灯并回到起点?
Input
连续T组数据输入,每组数据第一行给出三个正整数,分别表示地下迷宫的结点数N(1 < N <= 1000)、边数M(M <= 3000)和起始结点编号S,随后M行对应M条边,每行给出一对正整数,表示一条边相关联的两个顶点的编号。

Output
若可以点亮所有结点的灯,则输出从S开始并以S结束的序列,序列中相邻的顶点一定有边,否则只输出部分点亮的灯的结点序列,最后输出0,表示此迷宫不是连通图。
访问顶点时约定以编号小的结点优先的次序访问,点亮所有可以点亮的灯后,以原路返回的方式回到起点。

Sample Input
1
6 8 1
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5
Sample Output
1 2 3 4 5 6 5 4 3 2 1

提示:此题无论是否联通都要输出返回路径
题干描述不清楚。
**********/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int vis[1001],bian[3000][3000],s[1001],n,e;
void DFS(int a)
{
    s[e++]=a;              ///记录去时路径
    vis[a]=1;
    for(int i=1;i<=n;i++)   ///结点从1开始,不是0.
    {
        if(bian[a][i]&&!vis[i])
        {
            DFS(i);
            s[e++]=a;     ///记录返回路径
        }
    }
}
int main()
{
   int t,m,d,x,y;
   cin>>t;
   while(t--)
   {
       memset(vis,0,sizeof(vis));
       memset(bian,0,sizeof(bian));
       cin>>n>>m>>d;
       while(m--)
       {
           cin>>x>>y;
           bian[x][y]=bian[y][x]=1;
       }
       e=0;
       DFS(d);
       for(int i=0;i<e-1;i++)
       {
           cout<<s[i]<<" ";

       }
       cout<<s[e-1];
       if(2*n-1==e)
        cout<<endl;
       else
        cout<<" "<<0<<endl;
       /***
       if(e == n)
       {
           for(int i=0;i<e;i++)
            cout<<s[i]<<" ";
          for(int i=e-2;i>0;i--)
            cout<<s[i]<<" ";
          cout<<s[0]<<endl;
       }
       else
       {
           for(int i=0;i<e;i++)
               cout<<s[i]<<" ";
               cout<<0<<endl;
       }
       **********/
   }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dongjian2/article/details/89511748