|
| 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