import collections
# 迷宫题
maze= [[5, 5, 0, 0,0],
[3, 5, 4, 2, 3],
[4, 5, 3, 4, 3],
[4, 3, 5, 3, 2],
[2, 5, 3, 3, 5],
[5, 3, 4, 4, 3]]
# maze= [[1, 1,1],
# [1, 1, 1]]
ball=tuple((0,0))
hole=tuple((5, 4))
dmap = collections.defaultdict(lambda: collections.defaultdict(int))
w, h = len(maze), len(maze[0])
for x in range(w):
for y in range(h):
maze[x][y]= maze[x][y]-x-y
if maze[x][y]>0:
maze[x][y]=0
if maze[x][y]==0 and maze[x][y]<0:
maze[x][y]=1
# print(maze)
for dir in 'dlru': dmap[hole][dir] = hole
for x in range(w):
for y in range(h):
if maze[x][y] or (x, y) == hole: continue
dmap[(x, y)]['u'] = dmap[(x - 1, y)]['u'] if x > 0 and dmap[(x - 1, y)]['u'] else (x, y)
dmap[(x, y)]['l'] = dmap[(x, y - 1)]['l'] if y > 0 and dmap[(x, y - 1)]['l'] else (x, y)
for x in range(w - 1, -1, -1):
for y in range(h - 1, -1, -1):
if maze[x][y] or (x, y) == hole: continue
dmap[(x, y)]['d'] = dmap[(x + 1, y)]['d'] if x < w - 1 and dmap[(x + 1, y)]['d'] else (x, y)
dmap[(x, y)]['r'] = dmap[(x, y + 1)]['r'] if y < h - 1 and dmap[(x, y + 1)]['r'] else (x, y)
bmap = {ball: (0, '')}
distance = lambda pa, pb: abs(pa[0] - pb[0]) + abs(pa[1] - pb[1])
queue = collections.deque([(ball, 0, '')])
while queue:
front, dist, path = queue.popleft()
for dir in 'dlru':
if dir not in dmap[front]: continue
np = dmap[front][dir]
ndist = dist + distance(front, np)
npath = path + dir
if np not in bmap or (ndist, npath) < bmap[np]:
bmap[np] = (ndist, npath)
queue.append((np, ndist, npath))
# path_output= bmap[hole][1] if hole in bmap else '-1'
value_output=bmap[hole][0] if hole in bmap else '-1'
# print(path_output)
print(value_output)