Advertisement
kosievdmerwe

Untitled

Oct 1st, 2021
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. class Solution:
  2.     def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
  3.         W = len(dungeon)
  4.         H = len(dungeon[0])
  5.        
  6.         max_hp_needed = -sum(
  7.             dungeon[x][y]
  8.             for x in range(W)
  9.             for y in range(H)
  10.             if dungeon[x][y] < 0
  11.         ) + 1
  12.        
  13.         if max_hp_needed == 1:
  14.             return 1
  15.        
  16.         b, e = 1, max_hp_needed + 1
  17.         ans = max_hp_needed
  18.         while b < e:
  19.             m = (b + e) // 2
  20.             if self.canTraverse(dungeon, m):
  21.                 ans = m
  22.                 e = m
  23.             else:
  24.                 b = m + 1
  25.         return ans
  26.    
  27.     def canTraverse(self, dungeon: List[List[int]], hp: int) -> bool:
  28.         W = len(dungeon)
  29.         H = len(dungeon[0])
  30.        
  31.         prev_hp_row = [- hp - 1] * (W + 1)
  32.         cur_hp_row = [- hp - 1] * (W + 1)
  33.        
  34.         # Essentially this makes it as if we'll enter the dungeon
  35.         # from a room above the top-left room.
  36.         prev_hp_row[0] = hp  
  37.         for y in range(H):
  38.             for x in range(W):
  39.                 best_starting_hp = max(
  40.                     prev_hp_row[x],
  41.                     cur_hp_row[x - 1],
  42.                 )
  43.                 cur_hp_row[x] = best_starting_hp
  44.                
  45.                 # If you're dead stay dead
  46.                 if best_starting_hp <= 0:
  47.                     continue
  48.                 cur_hp_row[x] += dungeon[x][y]
  49.            
  50.             if y == H - 1:
  51.                 return cur_hp_row[W - 1] > 0
  52.            
  53.             prev_hp_row, cur_hp_row = cur_hp_row, prev_hp_row
  54.            
  55.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement