|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +CREATED AT: 2022年10月30日 |
| 4 | + |
| 5 | +URL: https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ |
| 6 | + |
| 7 | +GITHUB: https://github.com/Jiezhi/myleetcode |
| 8 | + |
| 9 | +FileName: 1293-ShortestPathInAGridWithObstaclesElimination |
| 10 | + |
| 11 | +Difficulty: Hard |
| 12 | + |
| 13 | +Desc: |
| 14 | + |
| 15 | +Tag: |
| 16 | + |
| 17 | +See: |
| 18 | + |
| 19 | +""" |
| 20 | +from tool import * |
| 21 | + |
| 22 | + |
| 23 | +class Solution: |
| 24 | + def shortestPath(self, grid: List[List[int]], k: int) -> int: |
| 25 | + """ |
| 26 | + Ref: https://leetcode.cn/problems/shortest-path-in-a-grid-with-obstacles-elimination/solution/wang-ge-zhong-de-zui-duan-lu-jing-by-leetcode-solu/ |
| 27 | + Runtime: 83 ms, faster than 94.55% |
| 28 | + Memory Usage: 15.5 MB, less than 66.91% |
| 29 | + m == grid.length |
| 30 | + n == grid[i].length |
| 31 | + 1 <= m, n <= 40 |
| 32 | + 1 <= k <= m * n |
| 33 | + grid[i][j] is either 0 or 1. |
| 34 | + grid[0][0] == grid[m - 1][n - 1] == 0 |
| 35 | + """ |
| 36 | + m, n = len(grid), len(grid[0]) |
| 37 | + if k >= m + n - 2 or (m == 1 and n == 1): |
| 38 | + return m + n - 2 |
| 39 | + k = min(k, m + n - 3) |
| 40 | + |
| 41 | + dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)] |
| 42 | + dq = deque([(0, 0, k, 1)]) |
| 43 | + |
| 44 | + seen = {(0, 0, k)} |
| 45 | + |
| 46 | + while dq: |
| 47 | + x, y, k, cnt = dq.popleft() |
| 48 | + for dx, dy in dirs: |
| 49 | + nx, ny = x + dx, y + dy |
| 50 | + if 0 <= nx < m and 0 <= ny < n: |
| 51 | + if grid[nx][ny] == 0 and (nx, ny, k) not in seen: |
| 52 | + if nx == m - 1 and ny == n - 1: |
| 53 | + return cnt |
| 54 | + seen.add((nx, ny, k)) |
| 55 | + dq.append((nx, ny, k, cnt + 1)) |
| 56 | + elif grid[nx][ny] == 1 and k > 0 and (nx, ny, k - 1) not in seen: |
| 57 | + seen.add((nx, ny, k - 1)) |
| 58 | + dq.append((nx, ny, k - 1, cnt + 1)) |
| 59 | + |
| 60 | + return -1 |
| 61 | + |
| 62 | + |
| 63 | +def test(): |
| 64 | + assert Solution().shortestPath(grid=[[0, 0, 0], [1, 1, 0], [0, 0, 0], [0, 1, 1], [0, 0, 0]], k=1) == 6 |
| 65 | + assert Solution().shortestPath(grid=[[0, 1, 1], [1, 1, 1], [1, 0, 0]], k=1) == -1 |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == '__main__': |
| 69 | + test() |
0 commit comments