题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
def theNext(kl, grid, m, n):
x, y = kl[-1][0], kl[-1][1]
ks = []
res = []
if y < n:
if x-1 < m:
if grid[x-1][y]!=1:
ks.append((x-1,y))
if x+1 < m:
if grid[x+1][y]!=1:
ks.append((x+1,y))
if x < m:
if y-1 < n:
if grid[x][y-1]!=1:
ks.append((x,y-1))
if y+1 < n:
if grid[x][y+1]!=1:
ks.append((x,y+1))
for k in ks:
if k not in kl and k[0] >=0 and k[1] >= 0:
res.append(kl+[k])
return res
def theCheck(kl, m,n):
if kl[-1] == (m, n):
return True
def thepath(init, grid, m, n, xx, yy):
paths = [[init]]
path = []
while True:
tmp = []
for p in paths:
tmp.extend(theNext(p, grid, m ,n))
paths = tmp
for p in paths:
if theCheck(p, xx, yy):
return p
shape = list(map(int, input().split()))
grid = []
for _ in range(shape[0]):
tmp = list(map(int, input().split()))
grid.append(tmp)
path = thepath((0,0), grid, shape[0], shape[1], shape[0]-1, shape[1]-1)
path = [f"({_[0]},{_[1]})" for _ in path]
print("\n".join(path))