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

来源:互联网 发布:暴走漫画淘宝 编辑:程序博客网 时间:2024/06/06 17:25

Problem Description

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

Input

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

 

Output

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

Example Input

16 8 11 22 33 44 55 66 43 61 5

Example Output

1 2 3 4 5 6 5 4 3 2 1



#include <stdio.h>#include <string.h>#include <stdlib.h>int map[1100][1100];int book[1100];int dis[1100];int n, m, s;int count;void DFS(int u){    int i;    book[u] = 1;    dis[count++] = u;   //记录去的轨迹    for(i = 1; i <= n; i++)    {        if(map[u][i] && !book[i])        {            DFS(i);            dis[count++] = u;       //记录来的轨迹        }    }}int main(){    int t, i, u, v;    scanf("%d", &t);    while(t--)    {        scanf("%d %d %d", &n, &m, &s);        memset(map, 0, sizeof(map));        memset(book, 0, sizeof(book));        memset(dis, 0, sizeof(dis));        for(i = 0; i < m; i++)        {            scanf("%d %d", &u, &v);            map[u][v] = map[v][u] = 1;        }        count  = 0;        DFS(s);        for(i = 0; i < count; i++)        {            if(i == 0)                printf("%d", dis[i]);            else                printf(" %d", dis[i]);        }        if(2*n-1 != count)      //来回两次,最后一个数只访问一次            printf(" 0");        printf("\n");    }    return 0;}