5-33 地下迷宫探索 (30分)
地道战是在抗日战争时期,在华北平原上抗日军民利用地道打击日本侵略者的作战方式。地道网是房连房、街连街、村连村的地下工事,如下图所示。
我们在回顾前辈们艰苦卓绝的战争生活的同时,真心钦佩他们的聪明才智。在现在和平发展的年代,对多数人来说,探索地下通道或许只是一种娱乐或者益智的游戏。本实验案例以探索地下通道迷宫作为内容。
假设有一个地下通道迷宫,它的通道都是直的,而通道所有交叉点(包括通道的端点)上都有一盏灯和一个开关。请问你如何从某个起点开始在迷宫中点亮所有的灯并回到起点?
输入格式:
输入第一行给出三个正整数,分别表示地下迷宫的节点数NNN(1
6 8 1
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5
输出样例1:
1 2 3 4 5 6 5 4 3 2 1
输入样例2:
6 6 6
1 2
1 3
2 3
5 4
6 5
6 4
输出样例2:
6 4 5 4 6 0
思路
关键词:深度优先搜索 /DFS
虽然广度优先也能做,但不是很对应这道题的遍历规则。
#include <stdio.h>
#include<stdlib.h>
/* 评测结果 时间 结果 得分 题目 编译器 用时(ms) 内存(MB) 用户
2016-08-30 11:17 答案正确 30 5-33 gcc 9 1 569985011
测试点结果 测试点 结果 得分/满分 用时(ms) 内存(MB)
测试点1 答案正确 10/10 2 1
测试点2 答案正确 10/10 1 1
测试点3 答案正确 5/5 1 1
测试点4 答案正确 5/5 9 1
查看代码*/
typedef struct node *Node;
struct node {
int Vertex;//目标节点
Node Next;
}**Map;
int*Usd;
Node Insert(Node,int);
Node New(int);
void Explore(int);
int main() {
int n,m,start;
scanf("%d%d%d",&n,&m,&start);
Map=(Node*)malloc(sizeof(Node)*(n+1));
Usd=(int*)malloc(sizeof(Node)*(n+1));
for(int i=0; i<n+1; i++) {
Map[i]=NULL;
Usd[i]=0;
}
for(int i=0; i<m; i++) {
int destination,Origin;
scanf("%d%d",&Origin,&destination);
Map[Origin]=Insert(Map[Origin],destination);
Map[destination]=Insert(Map[destination],Origin);
}
if(start<=n)
Explore(start);
int flag=0;
for(int i=1; i<n+1; i++) {
if(!Usd[i]) {
flag=1;
break;
}
}
if(flag)printf(" 0");//遍历失败输出0
return 0;
}
void Explore(int p) {
printf("%d",p);
Usd[p]=1;
while(Map[p]) {
Node temp=Map[p];
if(Usd[Map[p]->Vertex]==0) {
printf(" ");
Explore(Map[p]->Vertex);
printf(" %d",p);
}
Map[p]=Map[p]->Next;
free(temp);
}
}
Node Insert(Node p,int b) {
//printf("1");
if(!p||p->Vertex>b) {
// printf("2");
Node temp=New(b);
// printf("3");
temp->Next=p;
return temp;
} else {
p->Next=Insert(p->Next,b);
}
return p;
}
Node New(int K) {
Node temp=(Node)malloc(sizeof(struct node));
temp->Next=NULL;
temp->Vertex=K;
return temp;
}