Skip to content

Commit 0b236aa

Browse files
committed
Time: 27 ms (81.71%), Space: 18.7 MB (27.37%) - LeetHub
1 parent c8d34a9 commit 0b236aa

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# time complexity: O(m*n*log(m*n))
2+
# space complexity: O(m*n)
3+
from collections import defaultdict
4+
from heapq import heappop, heappush
5+
from typing import List
6+
7+
8+
class Solution:
9+
def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:
10+
ROW = len(maze)
11+
COL = len(maze[0])
12+
visited = defaultdict(lambda: float('inf'))
13+
minHp = [(0, start[0], start[1])]
14+
visited[(start[0], start[1])] = 0
15+
while minHp:
16+
currDist, currR, currC = heappop(minHp)
17+
if [currR, currC] == destination:
18+
return currDist
19+
for dR, dC in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
20+
nextR = currR
21+
nextC = currC
22+
nextDist = currDist
23+
while 0 <= nextR + dR < ROW and 0 <= nextC + dC < COL and maze[nextR + dR][nextC + dC] == 0:
24+
nextR += dR
25+
nextC += dC
26+
nextDist += 1
27+
if nextDist < visited[(nextR, nextC)]:
28+
heappush(minHp, (nextDist, nextR, nextC))
29+
visited[(nextR, nextC)] = nextDist
30+
return -1
31+
32+
33+
maze = [[0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [
34+
0, 0, 0, 1, 0], [1, 1, 0, 1, 1], [0, 0, 0, 0, 0]]
35+
start = [0, 4]
36+
destination = [4, 4]
37+
print(Solution().shortestDistance(maze, start, destination))
38+
maze = [[0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [
39+
0, 0, 0, 1, 0], [1, 1, 0, 1, 1], [0, 0, 0, 0, 0]]
40+
start = [0, 4]
41+
destination = [3, 2]
42+
print(Solution().shortestDistance(maze, start, destination))
43+
maze = [[0, 0, 0, 0, 0], [1, 1, 0, 0, 1], [
44+
0, 0, 0, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0]]
45+
start = [4, 3]
46+
destination = [0, 1]
47+
print(Solution().shortestDistance(maze, start, destination))

0 commit comments

Comments
 (0)