SDUT 3361 数据结构实验之图论四:迷宫探索

数据结构实验之图论四:迷宫探索

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

有一个地下迷宫,它的通道都是直的,而通道所有交叉点(包括通道的端点)上都有一盏灯和一个开关;请问如何从某个起点开始在迷宫中点亮所有的灯并回到起点?

Input

连续T组数据输入,每组数据第一行给出三个正整数,分别表示地下迷宫的结点数N(1 < N <= 1000)、边数M(M <= 3000)和起始结点编号S,随后M行对应M条边,每行给出一对正整数,表示一条边相关联的两个顶点的编号。

 

Output

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

Example Input

1
6 8 1
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5

Example Output

1 2 3 4 5 6 5 4 3 2 1

DQE:

走迷宫,注意DFS函数被执行时i的意义为站在i号顶点上,后面循环向各个方向探索返回后是回到了i号顶点,应输出i的编号,深度优先搜索题,略水。
 
 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 #define MVN 1010        //注意数组尺寸
 6 
 7 typedef struct AdjMatrix
 8 {
 9     int w;
10     char *info;
11 }AM;
12 
13 typedef struct MGraph
14 {
15     int vex[MVN];
16     AM arc[MVN][MVN];
17     int vexn,arcn;
18     int s;
19 }MG;
20 
21 void creat(MG &G)
22 {
23     int i,j,k;
24     for(i=1;i<=G.vexn;i++)
25         for(j=1;j<=G.vexn;j++)
26             G.arc[i][j].w=0;
27     for(k=1;k<=G.arcn;k++)
28     {
29         scanf("%d %d",&i,&j);
30         G.arc[i][j].w=G.arc[j][i].w=1;
31     }
32 }
33 
34 int count;    //计数变量
35 void DFS(MG &G,bool *f,int i)
36 {
37     f[i]=true;
38     count++;
39     if(i==G.s)
40         printf("%d",i);
41     else
42         printf(" %d",i);
43     int k;
44     for(k=1;k<=G.vexn;k++)
45         if(G.arc[i][k].w==1&&f[k]==false)
46         {
47             DFS(G,f,k);        //从i到邻接点
48             printf(" %d",i);    //回到i
49         }
50 }
51 
52 int main()
53 {
54     int t;
55     scanf("%d",&t);
56     while(t--)
57     {
58         MG G;
59         scanf("%d %d %d",&G.vexn,&G.arcn,&G.s);
60         creat(G);
61         bool visited[MVN]={false};
62         count=0;
63         DFS(G,visited,G.s);
64         if(count!=G.vexn)
65             printf(" 0");
66         printf("
");
67     }
68     return 0;
69 }
70 
71 /***************************************************
72 User name: ***
73 Result: Accepted
74 Take time: 0ms
75 Take Memory: 196KB
76 Submit time: 2016-11-18 21:18:16
77 ****************************************************/
原文地址:https://www.cnblogs.com/Leroscox/p/6044907.html