<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. Your initial position is at the <strong>top-left</strong> cell <code>(0, 0)</code>.</p>

<p>Starting from the cell <code>(i, j)</code>, you can move to one of the following cells:</p>

<ul>
	<li>Cells <code>(i, k)</code> with <code>j &lt; k &lt;= grid[i][j] + j</code> (rightward movement), or</li>
	<li>Cells <code>(k, j)</code> with <code>i &lt; k &lt;= grid[i][j] + i</code> (downward movement).</li>
</ul>

<p>Return <em>the minimum number of cells you need to visit to reach the <strong>bottom-right</strong> cell</em> <code>(m - 1, n - 1)</code>. If there is no valid path, return <code>-1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/01/25/ex1.png" style="width: 271px; height: 171px;" />
<pre>
<strong>Input:</strong> grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The image above shows one of the paths that visits exactly 4 cells.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/01/25/ex2.png" style="width: 271px; height: 171px;" />
<pre>
<strong>Input:</strong> grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]]
<strong>Output:</strong> 3
<strong>Explanation: </strong>The image above shows one of the paths that visits exactly 3 cells.
</pre>

<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/01/26/ex3.png" style="width: 181px; height: 81px;" />
<pre>
<strong>Input:</strong> grid = [[2,1,0],[1,0,0]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven that no path exists.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= grid[i][j] &lt; m * n</code></li>
	<li><code>grid[m - 1][n - 1] == 0</code></li>
</ul>

from bisect import bisect_left
from typing import List

class Mono:
    def __init__(self):
        self.I = []  # Indices
        self.V = []  # Values
        self.N = 0   # Current position in the monotonic stack
    
    def put(self, v: int):
        # Maintain a monotonic stack that keeps the minimum value at the front
        while self.V and self.V[-1] >= v:
            self.V.pop()
            self.I.pop()
        self.V.append(v)
        self.I.append(self.N)
        self.N += 1
    
    def query(self, g: int) -> int:
        # Query the minimum value among the last g values
        ii = self.N - g
        j = bisect_left(self.I, ii)
        if j < len(self.I):
            return self.V[j]
        return float('inf')  # Return a large value if no valid query

class Solution:
    def minimumVisitedCells(self, grid: List[List[int]]) -> int:
        Inf = float('inf')
        M = len(grid)
        N = len(grid[0])
        
        # Initialize monotonic stacks for rows and columns
        H = [Mono() for _ in range(M)]
        V = [Mono() for _ in range(N)]
        
        # Start from the bottom-right corner
        H[-1].put(1)
        V[-1].put(1)
        
        # Fill the last row from right to left
        for j in range(N - 2, -1, -1):
            g = grid[-1][j]
            if g == 0:
                v = Inf
            else:
                v = 1 + H[-1].query(g)
            H[-1].put(v)
            V[j].put(v)
        
        # Fill the last column from bottom to top
        for i in range(M - 2, -1, -1):
            g = grid[i][-1]
            if g == 0:
                v = Inf
            else:
                v = 1 + V[-1].query(g)
            H[i].put(v)
            V[-1].put(v)
        
        # Fill the rest of the grid
        for i in range(M - 2, -1, -1):
            for j in range(N - 2, -1, -1):
                g = grid[i][j]
                if g == 0:
                    v = Inf
                else:
                    v1 = V[j].query(g)
                    v2 = H[i].query(g)
                    v = 1 + min(v1, v2)
                H[i].put(v)
                V[j].put(v)
        
        # The result is the minimum number of cells to visit from (0, 0) to (m-1, n-1)
        r = H[0].query(1)
        return r if r < Inf else -1

# Example usage:
solution = Solution()
grid1 = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]]
print(solution.minimumVisitedCells(grid1))  # Output: 4

grid2 = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]]
print(solution.minimumVisitedCells(grid2))  # Output: 3

grid3 = [[2,1,0],[1,0,0]]
print(solution.minimumVisitedCells(grid3))  # Output: -1
2461