Advertisement
kosievdmerwe

Untitled

Sep 25th, 2021
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.28 KB | None | 0 0
  1. DELTAS = [(-1, 0), (0, -1), (1, 0), (0, 1)]
  2.  
  3. class Solution:
  4.     def shortestPath(self, grid: List[List[int]], k: int) -> int:
  5.         W = len(grid)
  6.         H = len(grid[0])
  7.        
  8.         if k >= W + H - 2:
  9.             return W + H - 2
  10.        
  11.         dist = [[None] * H for _ in range(W)]
  12.         dist[0][0] = 0
  13.        
  14.         obstacles = []
  15.         for x in range(W):
  16.             for y in range(H):
  17.                 if grid[x][y] == 1:
  18.                     obstacles.append((x, y))
  19.        
  20.         def min_neighbour(x: int, y: int) -> Optional[int]:
  21.             ans = None
  22.             for dx, dy in DELTAS:
  23.                 nx, ny = x + dx, y + dy
  24.                 if not (0 <= nx < W and 0 <= ny < H):
  25.                     continue
  26.                 if dist[nx][ny] is None:
  27.                     continue
  28.                 if ans is None or dist[nx][ny] < ans:
  29.                     ans = dist[nx][ny]
  30.             return ans
  31.                
  32.        
  33.         for ki in range(k + 1):
  34.             q = []  # tuples of (dist, x, y)
  35.             if ki == 0:
  36.                 q.append((0, 0, 0))
  37.             else:
  38.                 for x, y in obstacles:
  39.                     ndist = min_neighbour(x, y)
  40.                     if ndist is None:
  41.                         continue
  42.                     if dist[x][y] is None or ndist + 1 < dist[x][y]:
  43.                         q.append((ndist + 1, x, y))
  44.                 for cdist, x, y in q:
  45.                     dist[x][y] = cdist
  46.             heapify(q)
  47.            
  48.             while q:
  49.                 cdist, x, y = heappop(q)
  50.                 if dist[x][y] > cdist:
  51.                     continue
  52.                 for dx, dy in DELTAS:
  53.                     nx, ny = x + dx, y + dy
  54.                     if not (0 <= nx < W and 0 <= ny < H):
  55.                         continue
  56.                     if grid[nx][ny] == 1:
  57.                         continue
  58.                     ndist = cdist + 1
  59.                     if dist[nx][ny] is None or ndist < dist[nx][ny]:
  60.                         dist[nx][ny] = ndist
  61.                         heappush(q, (dist[nx][ny], nx, ny))
  62.                        
  63.             # for row in dist:
  64.             #     print(row)
  65.             # print()
  66.            
  67.         return dist[-1][-1] if dist[-1][-1] is not None else -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement