Advertisement
pavel_777

leet weekly 295-4

May 31st, 2022
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. # https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/
  2. from collections import deque
  3.  
  4. class Solution:
  5.     def minimumObstacles(self, grid: List[List[int]]) -> int:
  6.         # 0-1 bfs
  7.         y_max, x_max = len(grid), len(grid[0])
  8.         d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
  9.         distance = [[-1] * x_max for _ in range(y_max)]
  10.         q = deque([(0, 0, 0)])
  11.  
  12.         while q:
  13.             dist, r, c = q.popleft()
  14.             for dr, dc in d:
  15.                 y, x = r + dr, c + dc
  16.                 if 0 <= y < y_max and 0 <= x < x_max and distance[y][x] == -1:
  17.                     if grid[y][x] == 0:
  18.                         distance[y][x] = dist
  19.                         q.appendleft((dist, y, x))
  20.                     else:
  21.                         distance[y][x] = dist + 1
  22.                         q.append((dist + 1, y, x))
  23.                     if y == y_max - 1 and x == x_max - 1:
  24.                         return distance[-1][-1]
  25.         return distance[-1][-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement