<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>

# # TEMPLATE BY https://github.com/agrawalishaan
# # You are welcome to use this template. Please keep the link in your contest code to prevent automatic detection of copied content. Templates are allowed. Thanks!

# # Complexities:
# # Build: O(n)
# # Space: O(n)
# # Query/Update: O(log N)

# # baseFn: (val, i) => ...
# # combineFn: (leftVal, rightVal, leftLeftIdx, leftRightIdx, rightLeftIdx, rightRightIdx) => ...
# # tupleNametags: If baseFn returns a tuple, we can supply nametags for each value, like ('min', 'max'), used for debugging

# class SegmentTree:
#     def __init__(self, arr, baseFn, combine, tupleNametags=None):
#         self.n = len(arr)
#         self.arr = arr
#         self.tree = [None] * (4 * self.n)
#         self._combine = combine
#         self._baseFn = baseFn
#         self.tupleNametags = tupleNametags
#         self._build(1, 0, self.n - 1)

#     def _build(self, i, tl, tr):
#         if tl == tr:
#             self.tree[i] = self._baseFn(self.arr[tl])
#             return
#         tm = (tr + tl) // 2
#         self._build(2 * i, tl, tm)
#         self._build(2 * i + 1, tm + 1, tr)
#         self.tree[i] = self._combine(self.tree[2 * i], self.tree[2 * i + 1])

#     def _queryRecurse(self, i, tl, tr, l, r):
#         # print(f"Getting useful intersection from [{tl},{tr}] for query [{l},{r}]")
#         if l <= tl and tr <= r:
#             # print(f'Fully in bounds, returning node value:')
#             # print(f'{self._getPrintFormattedVal(self.tree[i], tl, tr)}\n')
#             return self.tree[i]

#         tm = (tl + tr) // 2
#         # print(f'left child: [{tl},{tm}], right child: [{tm + 1},{tr}]\n')

#         if l > tm:
#             # print(f'Left child [{tl},{tm}] would have no overlap, so only using right\n')
#             return self._queryRecurse(2 * i + 1, tm + 1, tr, l, r)
#         elif r < tm + 1:
#             # print(f'Right child [{tm+1},{tr}] would have no overlap, so only using left\n')
#             return self._queryRecurse(2 * i, tl, tm, l, r)

#         leftResult = self._queryRecurse(2 * i, tl, tm, l, r)
#         rightResult = self._queryRecurse(2 * i + 1, tm + 1, tr, l, r)
#         combinedResult = self._combine(leftResult, rightResult)
#         # print(f"Combining results for parent [{tl},{tr}] for query [{l},{r}]:\n"
#         #       f"  left useful: {self._getPrintFormattedVal(leftResult, max(l, tl), min(tm, r))}\n"
#         #       f"  right useful: {self._getPrintFormattedVal(rightResult, max(l, tm + 1), min(r, tr))}\n"
#         #       f"  -> combined useful: {self._getPrintFormattedVal(combinedResult, max(l, tl), min(r, tr))}\n")
#         return combinedResult

#     def _updateRecurse(self, i, tl, tr, posToBeUpdated):
#         # print(f'descending down to update, pos to be updated: {posToBeUpdated}, current node tl={tl}, tr={tr}')
#         if tl == tr:
#             # print(f'reached leaf node, updating then going back up and combining')
#             self.tree[i] = self._baseFn(self.arr[tl])
#             return
#         tm = (tl + tr) // 2
#         if posToBeUpdated <= tm:
#             self._updateRecurse(2 * i, tl, tm, posToBeUpdated)
#         else:
#             self._updateRecurse(2 * i + 1, tm + 1, tr, posToBeUpdated)
#         self.tree[i] = self._combine(self.tree[2 * i], self.tree[2 * i + 1])

#     def _getPrintFormattedVal(self, val, tl, tr):
#         subarray = self.arr[tl:tr + 1]
#         prefix = f'[{tl},{tr}] subarray: {subarray} '
#         if self.tupleNametags is None:
#             if isinstance(val, tuple):
#                 return prefix + f"({', '.join(str(v) for v in val)})"
#             return prefix + str(val)
#         return f'{prefix}({", ".join(f"{tag}: {v}" for tag, v in zip(self.tupleNametags, val))})'

#     def _line(self):
#         return '________________________________________'

#     ################ PUBLIC METHODS START HERE ################

#     def updateAndMutateArray(self, index, newVal):
#         # print(f'{self._line()} UPDATE CALLED, index={index}, newVal={newVal} {self._line()}')
#         self.arr[index] = newVal
#         self._updateRecurse(1, 0, self.n - 1, index)
#         # print(f'new array: {self.arr}')

#     def query(self, l, r):
#         # print(f'{self._line()} QUERY CALLED, l={l} r={r} {self._line()}')
#         # print(f'array: {self.arr}\n')
#         queryResult = self._queryRecurse(1, 0, self.n - 1, l, r)
#         # print(f'query result: {queryResult}')
#         return queryResult

#     # Gets the value at an index in O(1)
#     def getVal(self, i):
#         return self.arr[i]

#     def __str__(self):
#         result = []
#         def _printTree(i, tl, tr, indent):
#             if tl == tr:
#                 result.append(f'{" " * indent}{self._getPrintFormattedVal(self.tree[i], tl, tr)}')
#                 return
#             tm = (tl + tr) // 2
#             result.append(f'{" " * indent}{self._getPrintFormattedVal(self.tree[i], tl, tr)}')
#             _printTree(2 * i, tl, tm, indent + 4)
#             _printTree(2 * i + 1, tm + 1, tr, indent + 4)
#         _printTree(1, 0, self.n - 1, 0)
#         return f'{self._line()} SEGMENT TREE VISUALIZATION {self._line()}\n' + "\n".join(result)


# class Solution:
#     def minimumVisitedCells(self, grid: List[List[int]]) -> int:

#         def baseFn(val):
#             return val
#         def comb(a, b):
#             return min(a, b)
        
#         height = len(grid)
#         width = len(grid[0])

#         rows = [] # holds row STs
#         for i in range(height):
#             dp = [inf] * width
#             if i == height - 1:
#                 dp[-1] = 0
#             st = SegmentTree(dp, baseFn, comb)
#             rows.append(st)
        

#         cols = []
#         for i in range(width):
#             dp = [inf] * height
#             if i == width - 1:
#                 dp[-1] = 0
#             st = SegmentTree(dp, baseFn, comb)
#             cols.append(st)

        
#         for r in range(height - 1, -1, -1):
#             for c in range(width - 1, -1, -1):
#                 if r == height - 1 and c == width - 1:
#                     continue
#                 furthestRight = min(width - 1, grid[r][c] + c)
#                 furthestDown = min(height - 1, grid[r][c] + r)

#                 rowSt = rows[r]
#                 colSt = cols[c]
                
#                 resHere = inf
                
#                 # can query right if we aren't in the rightmost column
#                 if c != width - 1 and grid[r][c]:
#                     rightSmallest = rowSt.query(c + 1, furthestRight)
#                     resHere = rightSmallest + 1
                
#                 # can query down if we aren't in the last row
#                 if r != height - 1 and grid[r][c]:
#                     downSmallest = colSt.query(r + 1, furthestDown)
#                     resHere = min(resHere, 1 + downSmallest)
                
#                 rowSt.updateAndMutateArray(c, resHere)
#                 colSt.updateAndMutateArray(r, resHere)
        
#         res = rows[0].getVal(0)
#         return res + 1 if res != inf else -1







class Solution:
    def minimumVisitedCells(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        if m == 1 and n == 1:
            return 1
        
        # Initialize the queue with the starting point
        queue = deque([(0, 0)])
        level = 1
        
        # Initialize Union-Find structures
        usv = [[i for i in range(m + 1)] for _ in range(n)]
        ush = [[i for i in range(n + 1)] for _ in range(m)]
        
        while queue:
            level += 1
            for _ in range(len(queue)):
                r, c = queue.popleft()
                
                # Check downward moves
                nr = self.getRoot(r + 1, usv, c)
                while nr < m and nr <= r + grid[r][c]:
                    if nr == m - 1 and c == n - 1:
                        return level
                    queue.append((nr, c))
                    nr = self.doUnion(nr, nr + 1, usv, c)
                
                # Check rightward moves
                nc = self.getRoot(c + 1, ush, r)
                while nc < n and nc <= c + grid[r][c]:
                    if r == m - 1 and nc == n - 1:
                        return level
                    queue.append((r, nc))
                    nc = self.doUnion(nc, nc + 1, ush, r)
        
        # If no valid path is found
        return -1

    def getRoot(self, node: int, usAry: List[List[int]], i: int) -> int:
        while node != usAry[i][node]:
            usAry[i][node] = usAry[i][usAry[i][node]]
            node = usAry[i][node]
        return node

    def doUnion(self, node1: int, node2: int, usAry: List[List[int]], i: int) -> int:
        r1 = self.getRoot(node1, usAry, i)
        r2 = self.getRoot(node2, usAry, i)
        usAry[i][r1] = r2
        return r2
53900