题面:
http://poj.org/problem?id=2251
Description
You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.
Is an escape possible? If yes, how long will it take?Input
The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size).
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C.Output
Each maze generates one line of output. If it is possible to reach the exit, print a line of the form
Escaped in x minute(s).
where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the lineTrapped!Sample Input
3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 0 0 0Sample Output
Escaped in 11 minute(s). Trapped!
方案:
cube = []
row = 0
col = 0
lvl = 0
finestpath = []
tmppath = []
def getinput():
global row
global col
global lvl
lvl ,row, col = [int(x) for x in input().strip().split()]
for j in range(0,lvl):
matrix = []
for i in range(0, row):
line = [x for x in input().strip()]
matrix.append(line)
cube.append(matrix)
print(matrix)
slash = input()
if cube[lvl - 1][row - 1][col - 1] != "E":
return False
print(cube)
def findpath(z, y, x):
# 先判断坐标是否合法
if x >= col or x < 0 or y >= row or y < 0 or z >=lvl or z<0:
return
# 如果当前节点不是通路
if cube[z][y][x] == "#":
return
# 当前节点可用
tmppath.append((z,y,x))
# 当前节点是不是已经是出口
if z == lvl - 1 and y == row - 1 and x == col - 1:
if not finestpath:
finestpath[:] = tmppath[:]
else:
if len(finestpath) > len(tmppath):
finestpath[:] = tmppath[:]
# 在找下一个通路节点之前先把自己锁死
cube[z][y][x] = "#"
# 上下左右找通路
findpath(z , y - 1 , x) #同层,向上
findpath(z , y , x - 1) #同层,向左
findpath(z , y + 1 , x) #同层,向下
findpath(z , y , x + 1) #同层向右
findpath(z - 1, y, x) # 上一层
findpath(z + 1, y, x) # 下一层
# 从x,y开始,并经历过上左下右的递归搜索后,没有找到出口,则还原当前节点状态,并把自己从tmppath中移除,因为
# 当前节点不是通路的一份子
cube[z][y][x] = "."
tmppath.pop()
getinput()
findpath(0, 0 ,0)
print(finestpath)
#for ele in finestpath:
# print('('+str(ele[0])+','+str(ele[1])+')')