Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
the-maze-ii.py 1.23 KB
Copy Edit Raw Blame History
Allen Liu authored 2018-10-13 01:56 +08:00 . add complexity
# Time: O(max(r, c) * wlogw)
# Space: O(w)
import heapq
class Solution(object):
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
"""
start, destination = tuple(start), tuple(destination)
def neighbors(maze, node):
for dir in [(-1, 0), (0, 1), (0, -1), (1, 0)]:
cur_node, dist = list(node), 0
while 0 <= cur_node[0]+dir[0] < len(maze) and \
0 <= cur_node[1]+dir[1] < len(maze[0]) and \
not maze[cur_node[0]+dir[0]][cur_node[1]+dir[1]]:
cur_node[0] += dir[0]
cur_node[1] += dir[1]
dist += 1
yield dist, tuple(cur_node)
heap = [(0, start)]
visited = set()
while heap:
dist, node = heapq.heappop(heap)
if node in visited: continue
if node == destination:
return dist
visited.add(node)
for neighbor_dist, neighbor in neighbors(maze, node):
heapq.heappush(heap, (dist+neighbor_dist, neighbor))
return -1
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search