华为迷宫问题求解

迷宫问题求解

在这里插入图片描述


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)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值