题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
'''
该递归方法在有多解时,会把所有解的路径返回出来,
因为每当有一个递归
到达目的地或者遇到死路时,递归会返回到岔路口地区
'''
while True:
try:
#构造迷宫
m,n=list(map(int,input().split()))
maze=[]
for k in range(m):
maze.append(list(map(int,input().split())))
def step(i, j, pos=[(0,0)]):
#看能否向下:
if i+1<=m-1 and maze[i+1][j]==0 and (i+1,j) not in pos:
step(i+1, j, pos+[(i+1,j)]) # 注意不能用pos.append()
# 看能否向上:
if i-1>=0 and maze[i-1][j]==0 and (i-1,j) not in pos:
step(i-1, j, pos+[(i-1,j)])
# 看能否向右:
if j+1<=n-1 and maze[i][j+1]==0 and (i,j+1)not in pos:
step(i, j+1, pos+[(i,j+1)])
# 看能否向左:
if j-1>=0 and maze[i][j-1]==0 and (i,j-1) not in pos:
step(i, j-1, pos+[(i,j-1)])
if i==m-1 and j==n-1:
for p in pos:
print('('+str(p[0])+','+str(p[1])+')') # 注意不能用print(p)
step(0,0)
except:
break
该递归方法在有多解时,会把所有解的路径返回出来,
因为每当有一个递归
到达目的地或者遇到死路时,递归会返回到岔路口地区
'''
while True:
try:
#构造迷宫
m,n=list(map(int,input().split()))
maze=[]
for k in range(m):
maze.append(list(map(int,input().split())))
def step(i, j, pos=[(0,0)]):
#看能否向下:
if i+1<=m-1 and maze[i+1][j]==0 and (i+1,j) not in pos:
step(i+1, j, pos+[(i+1,j)]) # 注意不能用pos.append()
# 看能否向上:
if i-1>=0 and maze[i-1][j]==0 and (i-1,j) not in pos:
step(i-1, j, pos+[(i-1,j)])
# 看能否向右:
if j+1<=n-1 and maze[i][j+1]==0 and (i,j+1)not in pos:
step(i, j+1, pos+[(i,j+1)])
# 看能否向左:
if j-1>=0 and maze[i][j-1]==0 and (i,j-1) not in pos:
step(i, j-1, pos+[(i,j-1)])
if i==m-1 and j==n-1:
for p in pos:
print('('+str(p[0])+','+str(p[1])+')') # 注意不能用print(p)
step(0,0)
except:
break
【牛客站内】华为机试题—中等 文章被收录于专栏
【牛客站内】华为机试题练习记录