2577. Minimum Time to Visit a Cell In a Grid
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```python3 []
import heapq
from typing import List

class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:
        if grid[0][1] > 1 and grid[1][0] > 1:
            return -1

        num_rows, num_cols = len(grid), len(grid[0])
        possible_moves = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        explored = set()

        priority_queue = [(grid[0][0], 0, 0)]

        while priority_queue:
            current_time, current_x, current_y = heapq.heappop(priority_queue)

            if (current_x, current_y) == (num_rows - 1, num_cols - 1):
                return current_time

            if (current_x, current_y) in explored:
                continue
            explored.add((current_x, current_y))

            for move_x, move_y in possible_moves:
                next_x, next_y = current_x + move_x, current_y + move_y

                if not self._is_valid_position(explored, next_x, next_y, num_rows, num_cols):
                    continue

                waiting_time = 1 if (grid[next_x][next_y] - current_time) % 2 == 0 else 0
                new_time = max(grid[next_x][next_y] + waiting_time, current_time + 1)
                heapq.heappush(priority_queue, (new_time, next_x, next_y))

        return -1

    def _is_valid_position(self, explored, next_x, next_y, num_rows, num_cols):
        return 0 <= next_x < num_rows and 0 <= next_y < num_cols and (next_x, next_y) not in explored

```
['Python3']