Leetcode #2617: Minimum Number of Visited Cells in a Grid
In this guide, we solve Leetcode #2617 Minimum Number of Visited Cells in a Grid in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed m x n integer matrix grid. Your initial position is at the top-left cell (0, 0).
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Stack, Breadth-First Search, Union Find, Array, Dynamic Programming, Matrix, Monotonic Stack, Heap (Priority Queue)
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
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]
Complexity
The time complexity is and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.