python迷宫
def tracback(x, y, dis, n):
if pos[x][y] == '#':
return float('inf')
if pos[x][y] == 'E':
if pos[x][y] != '*':
return dis
pos[x][y] = '#'
if x+1 == n:
a = tracback(0, y, dis + 1, n)
else:
a = tracback(x + 1, y, dis + 1, n)
if x-1 == -1:
b = tracback(n-1, y, dis + 1, n)
else:
b = tracback(x - 1, y, dis + 1, n)
if y+1 == n:
c = tracback(x, 0, dis + 1, n)
else:
c = tracback(x, y+1, dis + 1, n)
if y-1 == -1:
d = tracback(x, n-1, dis + 1, n)
else:
d = tracback(x, y-1, dis + 1, n)
res = min(a, b, c, d)
pos[x][y] = '.'
return res
n = int(input().strip())
pos = []
start = [0, 0]
for i in range(n):
temp = input().strip()
row = []
for j in range(n):
if temp[j] == 'S':
start = [i, j]
row.append(temp[j])
pos.append(row)
res = tracback(start[0], start[1], 0, n)
if res == float('inf'):
print(-1)
else:
print(res)