题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#要知道迷宫的路可能会拐弯可能会出现往上走往左走这样的情况,所以也得判断这个位置是否走过
#注意走到终点不是直接return,而是打印,否则return到最上层不是res里面不就空了
def dfs(list1, m,n,i,j,res):
if i < 0 or i >=m or j < 0 or j >= n or list1[i][j] == 1:
return
res.append((i,j))
#global res_min
if i == m-1 and j== n-1:
for tu in res:
#这样输出说是格式不对,要全都是字符,而且直接输出元组的中间的空格可能也不对
#print(tu)
print('(' + str(tu[0]) + ',' + str(tu[1]) + ')')
return
if i <= m-2 and list1[i+1][j] ==0:
if (i+1,j) not in res:
dfs(list1, m,n, i+1, j, res)
if j <= n-2 and list1[i][j+1] ==0:
if (i,j+1) not in res:
dfs(list1, m,n, i, j+1, res)
if i >= 1 and list1[i-1][j] ==0:
if (i-1,j) not in res:
dfs(list1, m,n, i-1, j, res)
if j >= 1 and list1[i][j-1] ==0:
if (i,j-1) not in res:
dfs(list1, m,n, i, j-1, res)
res.pop()
return
m, n = map(int, (input().split()))
list1 = []
for i in range(m):
list1.append(list(map(int, input().split())))
res = []
dfs(list1, m, n, 0, 0, res)
