代码拉取完成,页面将自动刷新
# Time: O(max(r, c) * wlogw)
# Space: O(w^2)
import heapq
class Solution(object):
def findShortestWay(self, maze, ball, hole):
"""
:type maze: List[List[int]]
:type ball: List[int]
:type hole: List[int]
:rtype: str
"""
ball, hole = tuple(ball), tuple(hole)
dirs = {'u' : (-1, 0), 'r' : (0, 1), 'l' : (0, -1), 'd': (1, 0)}
def neighbors(maze, node):
for dir, vec in dirs.iteritems():
cur_node, dist = list(node), 0
while 0 <= cur_node[0]+vec[0] < len(maze) and \
0 <= cur_node[1]+vec[1] < len(maze[0]) and \
not maze[cur_node[0]+vec[0]][cur_node[1]+vec[1]]:
cur_node[0] += vec[0]
cur_node[1] += vec[1]
dist += 1
if tuple(cur_node) == hole:
break
yield tuple(cur_node), dir, dist
heap = [(0, '', ball)]
visited = set()
while heap:
dist, path, node = heapq.heappop(heap)
if node in visited: continue
if node == hole: return path
visited.add(node)
for neighbor, dir, neighbor_dist in neighbors(maze, node):
heapq.heappush(heap, (dist+neighbor_dist, path+dir, neighbor))
return "impossible"
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。