1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
the-maze-iii.py 1.35 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 7年前 . add complexity
# 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"
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助