class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
m, n = len(dungeon), len(dungeon[0])
memo = [[[None] * 2 for _ in range(n)] for _ in range(m)]
def check(h, i, j):
if memo[i][j][0] and h >= memo[i][j][0]:
return True
if memo[i][j][1] and h <= memo[i][j][1]:
return False
if h <= 0:
return False
result = None
if i == m-1 and j == n-1:
result = h + dungeon[i][j] > 0
elif i == m-1:
result = check(h + dungeon[i][j], i, j+1)
elif j == n-1:
result = check(h + dungeon[i][j], i+1, j)
else:
result = check(h + dungeon[i][j], i+1, j) or check(h + dungeon[i][j], i, j+1)
if result:
memo[i][j][0] = h
return True
else:
memo[i][j][1] = h
return False
low, high = 0, 2**31
while low < high:
mid = low + (high-low)//2
if check(mid, 0, 0):
high = mid
else:
low = mid + 1
return low
1621A - Stable Arrangement of Rooks | 472A - Design Tutorial Learn from Math |
1368A - C+= | 450A - Jzzhu and Children |
546A - Soldier and Bananas | 32B - Borze |
1651B - Prove Him Wrong | 381A - Sereja and Dima |
41A - Translation | 1559A - Mocha and Math |
832A - Sasha and Sticks | 292B - Network Topology |
1339A - Filling Diamonds | 910A - The Way to Home |
617A - Elephant | 48A - Rock-paper-scissors |
294A - Shaass and Oskols | 1213A - Chips Moving |
490A - Team Olympiad | 233A - Perfect Permutation |
1360A - Minimal Square | 467A - George and Accommodation |
893C - Rumor | 227B - Effective Approach |
1534B - Histogram Ugliness | 1611B - Team Composition Programmers and Mathematicians |
110A - Nearly Lucky Number | 1220B - Multiplication Table |
1644A - Doors and Keys | 1644B - Anti-Fibonacci Permutation |