Minimum Time to Visit a Cell In a Grid — LeetCode 2577 Python Solution

HardBreadth-First SearchGraphArrayMatrixShortest PathHeap (Priority Queue)
Problem
#2577
Reading time
5 min

The problem

You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col]. You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right.

Example

Input
grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]]
Output
7
Explanation
One of the paths that we can take is the following:

Python solution

Python
class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:
        if grid[0][1] > 1 and grid[1][0] > 1:
            return -1
        m, n = len(grid), len(grid[0])
        dist = [[inf] * n for _ in range(m)]
        dist[0][0] = 0
        q = [(0, 0, 0)]
        dirs = (-1, 0, 1, 0, -1)
        while 1:
            t, i, j = heappop(q)
            if i == m - 1 and j == n - 1:
                return t
            for a, b in pairwise(dirs):
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n:
                    nt = t + 1
                    if nt < grid[x][y]:
                        nt = grid[x][y] + (grid[x][y] - nt) % 2
                    if nt < dist[x][y]:
                        dist[x][y] = nt
                        heappush(q, (nt, x, y))

Complexity

MeasureComplexity
TimeO(m \times n \times \log (m \times n))
SpaceO(m \times n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2577. Minimum Time to Visit a Cell In a Grid is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2577. Minimum Time to Visit a Cell In a Grid?
LeetCode 2577. Minimum Time to Visit a Cell In a Grid is rated Hard on LeetCode.
What is the time complexity of LeetCode 2577. Minimum Time to Visit a Cell In a Grid?
The Python solution on this page runs in O(m \times n \times \log (m \times n)).
What is the space complexity of LeetCode 2577. Minimum Time to Visit a Cell In a Grid?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 2577. Minimum Time to Visit a Cell In a Grid cover?
LeetCode 2577. Minimum Time to Visit a Cell In a Grid is tagged Breadth-First Search, Graph, Array, Matrix, Shortest Path and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview