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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

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

Hint

Source

xam

dfs。。

直接搜索, 遇到可以点亮的灯就直接存下来并让计数变量加一。一直到前面没有可以点亮的灯了再原路返回。

然后把返回路径再保存一遍。 比较这时计数变量和灯的个数并分情况输出。

#include <bits/stdc++.h>

using namespace std;

bool Map[1010][1010], a[1010];
int b[1010];
int n, m, s, cnt;
void dfs(int s);
int main(){
	ios::sync_with_stdio(0);
	int t, u, v;
	cin >> t;
	while(t--){
        cin >> n >> m >> s;
        memset(Map, false, sizeof(Map));
        memset(a, true, sizeof(a));
        for(int i = 1; i <= m; i++){
            cin >> u >> v;
            Map[u][v] =  Map[v][u] = true;
        }
        cnt = 0;
        dfs(s);
        if(cnt >= 2*n - 1){
            for(int i = 1; i < cnt; i++)
                cout << b[i] << " ";
            cout << b[1] << endl;
        }
        else{
            for(int i = 1; i <= cnt; i++)
                cout << b[i] << " ";
            cout << "0" << endl;
        }
	}
    return 0;
}


void dfs(int k){
    b[++cnt] = k;
    a[k] = false;
    for(int i = 1; i<= n; i++){
        if(Map[k][i] && a[i]){
            dfs(i);
            b[++cnt] = k;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zx__zh/article/details/82082493