一个迷宫是由N(无限制,你可以取任何值,比如20,50,90,1000等)多个房间组成,每两个相邻的房间之间有可能会有一条通道。这个通道有个神奇的特性,那就是当一个人从一个房间经过某条通道进入到另一个房间后,他身后那条通道会立即消失,同时其他三个方向上可能会出现新的通道,当然也可能没有新通道出现,那就证明这是个死胡同,走不通,但此时你已经退不回去了,说的粗俗点就是“你挂了”。
现在让你编一个程序,在一个给定的迷宫里面找到所有潜在可能的逃生路径,并将他们打印出来。注意:有可能会有环路哦!
要求:
1、程序尽可能简练,算法的时间和空间复杂度没有强制要求,但要合情理。假如,你的程序处理1000个房间时,用了20多秒,那肯定是不合格的。
2、将所有逃生路径全部输出,但不要重复输出相同的路径。
3、程序必须能够正确处理可能存在的环路情况。
例如:
这个示例中有环路,编号为0的房间为出口处。
如果从房间号为127的格子出发,那么存在两条逃生路径。因此,你的程序应该输出像下面这样的结果:
starting in room 127
path found
in 127 go south
in 17 go south
in 8 go south
in 12 go west
in 25 go west
outside
path found
in 127 go south
in 17 go west
in 93 go south
in 25 go west
outside
我的解法:
-
#include <stdio.h>
-
#include <unistd.h>
-
-
enum direction {
-
EAST,
-
WEST,
-
SOUTH,
-
NORTH,
-
DIR_NUM,
-
};
-
-
char *dir_str[DIR_NUM] = {"east", "west", "south", "north"};
-
-
struct room {
-
int number;
-
enum direction open;
-
struct room *doors[DIR_NUM];
-
};
-
-
struct room rooms[10] = {
-
{ //0
-
.number = 4,
-
.open = DIR_NUM,
-
.doors = {NULL},
-
},
-
{ //1
-
.number = 127,
-
.open = DIR_NUM,
-
.doors = {rooms+2, NULL, rooms+4, NULL},
-
},
-
{ //2
-
.number = 61,
-
.open = DIR_NUM,
-
.doors = {NULL, NULL, rooms+5, NULL},
-
},
-
{ //3
-
.number = 93,
-
.open = DIR_NUM,
-
.doors = {rooms+4, NULL, rooms+7, rooms},
-
},
-
{ //4
-
.number = 17,
-
.open = DIR_NUM,
-
.doors = {rooms+5, rooms+3, rooms+8, NULL},
-
},
-
{ //5
-
.number = 43,
-
.open = DIR_NUM,
-
.doors = {rooms, NULL, NULL, NULL},
-
},
-
{ //6
-
.number = 0,
-
.open = DIR_NUM,
-
.doors = {NULL},
-
},
-
{ //7
-
.number = 25,
-
.open = DIR_NUM,
-
.doors = {rooms+8, rooms+6, NULL, rooms+3},
-
},
-
{ //8
-
.number = 8,
-
.open = DIR_NUM,
-
.doors = {NULL, NULL, rooms+9, rooms+4},
-
},
-
{ //9
-
.number = 12,
-
.open = DIR_NUM,
-
.doors = {rooms+5, rooms+7, NULL, rooms+8},
-
},
-
};
-
int room_num = 10;
-
-
int exit_room_number = 0;
-
-
struct room *start_room = rooms+1;
-
-
void print_path()
-
{
-
struct room *start = start_room;
-
-
printf("path found\n");
-
while (start->open != DIR_NUM)
-
{
-
printf("\t in %d go %s.\n", start->number, dir_str[start->open]);
-
start = start->doors[start->open];
-
}
-
printf("outside\n\n");
-
}
-
-
void path_find(struct room *start)
-
{
-
int i;
-
-
if ( start->number == exit_room_number)
-
{
-
print_path();
-
return;
-
}
-
-
if ( start->open != DIR_NUM)
-
return;
-
-
if ( start->doors[EAST] != NULL)
-
{
-
start->open = EAST;
-
path_find(start->doors[EAST]);
-
}
-
-
if ( start->doors[WEST] != NULL)
-
{
-
start->open = WEST;
-
path_find(start->doors[WEST]);
-
}
-
-
if ( start->doors[SOUTH] != NULL)
-
{
-
start->open = SOUTH;
-
path_find(start->doors[SOUTH]);
-
}
-
-
if ( start->doors[NORTH] !=NULL)
-
{
-
start->open = NORTH;
-
path_find(start->doors[NORTH]);
-
}
-
-
start->open = DIR_NUM;
-
-
return;
-
-
}
-
-
int main(int argc, char*argv[])
-
{
-
-
printf("starting in room %d\n", start_room->number);
-
path_find(start_room);
-
-
return 0;
-
}
阅读(3492) | 评论(0) | 转发(0) |