题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
dfs的方法,此题相当于一个四叉树,每次可以选择走上下左右任何方向,只要不越界。如果发现某条路径不通,需要注意把该不通路径中所有的轨迹删掉。
a, b = map(int, str(input()).split())
route_c = []#存放走过的轨迹
maze = []#接收输入数组
path = [[0 for i in range(b)] for i in range(a)]#记录哪个轨迹点曾经走过,确保不走回头路
#path = np.zeros([a, b])
#print(path)
for j in range(a):
l = [i for i in list(map(int, str(input()).split()))]
maze.append(l)
def find_r(m, n, route_c):
#nonlocal route_c
#route_c_l = route_c
if maze[m][n] == 1:
return
else:
route_c.append([m, n])
path[m][n] = 1
if m == a-1 and n == b-1:
for ele in route_c:
print('(' + str(ele[0])+','+str(ele[1])+')')
return
l_rc = len(route_c)
#back_r = -1 if l_rc<2 else route_c[-2][0]
if m < a-1 and path[m+1][n] == 0 :
find_r(m+1, n, route_c)
#l_rc = 2
route_c = route_c[:l_rc]#能够走到这一步,说明该路径不通,则把轨迹点都删掉。
l_rc = len(route_c)
if n < b-1 and path[m][n+1] == 0 :
find_r(m, n+1, route_c)
route_c = route_c[:l_rc]
l_rc = len(route_c)
if m > 0 and path[m-1][n] == 0:
find_r(m-1, n, route_c)
route_c = route_c[:l_rc]
l_rc = len(route_c)
if n > 0 and path[m][n-1] == 0:
find_r(m, n-1, route_c)
route_c = route_c[:l_rc]
find_r(0, 0, route_c)