Python:
class Solution:
def minimumTime(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
if grid[0][1] > 1 and grid[1][0] > 1:
return -1
heap = [(0 ,0 ,0)] # time, r, c
visited = set()
while heap:
time, r, c = heapq.heappop(heap)
if (r, c) == (rows - 1, cols - 1):
return time
if (r, c) in visited:
continue
#We have to mark visited here because we need to re-visit all neis if we dont have enough time to move.
visited.add((r, c))
for rd, cd in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
if 0 <= rd < rows and 0 <= cd < cols and (rd, cd) not in visited:
wait = 1 if (grid[rd][cd] - time) % 2 == 0 else 0
next_time = max(time + 1, grid[rd][cd] + wait)
heapq.heappush(heap, (next_time, rd, cd))
return -1
Debug sml chỗ mark visited, mark ngay sau khi check not in visited là sẽ miss count




