#2577

Minimum Time to Visit a Cell In a Grid

Hard
ArrayBreadth-First SearchGraph TheoryHeap (Priority Queue)MatrixShortest PathGraph TraversalDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(E log V)
Space
O(1)
O(m * n)
💡

Intuition

Time O(E log V)Space O(m * n)

The optimal solution uses a priority queue (min-heap) to explore the grid in a way that always expands the least time-consuming path first. This is similar to Dijkstra's algorithm for finding the shortest path in a graph.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a priority queue and add the starting cell (0, 0) with time 0.
  2. 2Step 2: While the queue is not empty, extract the cell with the minimum time.
  3. 3Step 3: If this cell is the bottom-right cell, return the time.
  4. 4Step 4: For each valid adjacent cell, calculate the time needed to reach it and add it to the queue if it can be visited.
  5. 5Step 5: Keep track of visited cells to avoid cycles.
solution.py18 lines
1import heapq
2
3def minTimeToVisitCell(grid):
4    m, n = len(grid), len(grid[0])
5    pq = [(0, 0, 0)]  # (time, x, y)
6    visited = set()
7    while pq:
8        time, x, y = heapq.heappop(pq)
9        if (x, y) in visited:
10            continue
11        visited.add((x, y))
12        if x == m - 1 and y == n - 1:
13            return time
14        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
15            nx, ny = x + dx, y + dy
16            if 0 <= nx < m and 0 <= ny < n and time + 1 >= grid[nx][ny]:
17                heapq.heappush(pq, (max(time + 1, grid[nx][ny]), nx, ny))
18    return -1

Complexity note: The time complexity is O(E log V) where E is the number of edges (possible moves) and V is the number of vertices (cells). The space complexity is O(m * n) due to the visited array.

  • 1Using a priority queue helps in exploring the least time-consuming paths first.
  • 2Tracking visited cells prevents cycles and unnecessary re-exploration.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.