题解 | #迷宫问题#Python解法一看就懂
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
def get_path(pos, matrix):
i, j = pos[0], pos[1]
n, m = len(matrix), len(matrix[0])
if not 0 <= i < n or not 0 <= j < m or not matrix[i][j] == 0: return
global cur_path, res
cur_path.append((i, j))
if i == n - 1 and j == m - 1: #到达终点
if not res or len(cur_path) < len(res): #若res为空或cur_path比res短
res = list(cur_path)
return
matrix[i][j] = 1
get_path([i + 1, j], matrix)
get_path([i - 1, j], matrix)
get_path([i, j + 1], matrix)
get_path([i, j - 1], matrix)
matrix[i][j] = 0
cur_path.pop()
while True:
try:
N, M = map(int, input().split())
matrix = []
for _ in range(N):
matrix.append(list(map(int, input().split())))
cur_path, res = [], []
get_path([0,0], matrix)
#print(res)
for pos in res:
print('({},{})'.format(pos[0], pos[1])) #要输出成字符形式
except:
break