#2617

Minimum Number of Visited Cells in a Grid

Hard
ArrayDynamic ProgrammingStackBreadth-First SearchUnion-FindHeap (Priority Queue)MatrixMonotonic StackBreadth-First SearchPriority QueueDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses a breadth-first search (BFS) with a priority queue to efficiently explore the grid. By prioritizing cells based on their potential to reach the destination, we minimize the number of cells visited.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a priority queue and start from the top-left cell (0, 0) with a distance of 1.
  2. 2Step 2: For each cell, calculate the valid rightward and downward moves based on the cell's value.
  3. 3Step 3: Use the priority queue to explore cells in order of their distance, ensuring the shortest path is found first.
  4. 4Step 4: If the bottom-right cell is reached, return the count of visited cells; otherwise, return -1 if no path exists.
solution.py22 lines
1# Full working Python code
2import heapq
3
4def minVisitedCells(grid):
5    m, n = len(grid), len(grid[0])
6    pq = [(1, 0, 0)]  # (steps, row, col)
7    visited = set()
8    visited.add((0, 0))
9
10    while pq:
11        steps, i, j = heapq.heappop(pq)
12        if (i, j) == (m - 1, n - 1):
13            return steps
14        for k in range(j + 1, min(n, j + grid[i][j] + 1)):
15            if (i, k) not in visited:
16                visited.add((i, k))
17                heapq.heappush(pq, (steps + 1, i, k))
18        for k in range(i + 1, min(m, i + grid[i][j] + 1)):
19            if (k, j) not in visited:
20                visited.add((k, j))
21                heapq.heappush(pq, (steps + 1, k, j))
22    return -1

Complexity note: The time complexity is O(n log n) due to the priority queue operations, where n is the number of cells. The space complexity is O(n) for storing visited cells and the priority queue.

  • 1Understanding how to navigate the grid based on cell values is crucial.
  • 2Using a priority queue can significantly optimize the search process.

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