Minimum Number of Visited Cells in a Grid Problem
Description
LeetCode Problem 2617.
You are given a 0-indexed m x n integer matrix grid. Your initial position is at the top-left cell (0, 0).
Starting from the cell (i, j), you can move to one of the following cells:
- Cells
(i, k)withj < k <= grid[i][j] + j(rightward movement), or - Cells
(k, j)withi < k <= grid[i][j] + i(downward movement).
Return the minimum number of cells you need to visit to reach the bottom-right cell (m - 1, n - 1). If there is no valid path, return -1.
Example 1:

Input: grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]]
Output: 4
Explanation: The image above shows one of the paths that visits exactly 4 cells.
Example 2:

Input: grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]]
Output: 3
Explanation: The image above shows one of the paths that visits exactly 3 cells.
Example 3:

Input: grid = [[2,1,0],[1,0,0]]
Output: -1
Explanation: It can be proven that no path exists.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10^51 <= m * n <= 10^50 <= grid[i][j] < m * ngrid[m - 1][n - 1] == 0
Solution
Approach: One Min-Heap per Row and per Column
Let dist[i][j] be the fewest cells visited to reach (i, j) from (0, 0), counting both ends; dist[0][0] = 1 and unreachable cells stay at -1.
A cell (i, j) is entered either from a cell (i, j') to its left in the same row with j' + grid[i][j'] >= j, or from a cell (i', j) above it in the same column with i' + grid[i'][j] >= i. We want the source with the smallest dist.
Keep a min-heap per row holding (dist, column) and a min-heap per column holding (dist, row). Process cells in row-major order. For cell (i, j), pop entries from the top of row heap i while they can no longer reach column j (and similarly for column heap j and row i): since we only move forward, an entry that cannot reach j cannot reach any later cell either. If a heap still has a top, dist[i][j] can be improved to its distance plus 1. If the cell is reachable, push it into its row heap and its column heap. The answer is dist[m - 1][n - 1].
Complexity: O(mn log(mn)) time and O(mn) space, where m and n are the number of rows and columns.
from heapq import heappop, heappush
class Solution:
def minimumVisitedCells(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dist = [[-1] * n for _ in range(m)]
dist[0][0] = 1
row = [[] for _ in range(m)]
col = [[] for _ in range(n)]
for i in range(m):
for j in range(n):
while row[i] and grid[i][row[i][0][1]] + row[i][0][1] < j:
heappop(row[i])
if row[i] and (dist[i][j] == -1 or dist[i][j] > row[i][0][0] + 1):
dist[i][j] = row[i][0][0] + 1
while col[j] and grid[col[j][0][1]][j] + col[j][0][1] < i:
heappop(col[j])
if col[j] and (dist[i][j] == -1 or dist[i][j] > col[j][0][0] + 1):
dist[i][j] = col[j][0][0] + 1
if dist[i][j] != -1:
heappush(row[i], (dist[i][j], j))
heappush(col[j], (dist[i][j], i))
return dist[-1][-1]