Check if There is a Path With Equal Number of 0's And 1's Problem
Description
LeetCode Problem 2510.
You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1).
Return true if there is a path from (0, 0) to (m - 1, n - 1) that visits an equal number of 0's and 1's. Otherwise return false.
Example 1:

Input: grid = [[0,1,0,0],[0,1,0,0],[1,0,1,0]]
Output: true
Explanation: The path colored in blue in the above diagram is a valid path because we have 3 cells with a value of 1 and 3 with a value of 0. Since there is a valid path, we return true.
Example 2:

Input: grid = [[1,1,0],[0,0,1],[1,0,0]]
Output: false
Explanation: There is no path in this grid with an equal number of 0's and 1's.
Constraints:
m == grid.lengthn == grid[i].length2 <= m, n <= 100grid[i][j]is either0or1.
Solution
Approach: Memoized DFS
Every path from the top-left to the bottom-right visits m + n - 1 cells. If that number is odd the counts cannot be equal, so the answer is false. Otherwise a valid path has exactly s = (m + n - 1) / 2 ones.
Run a DFS over (i, j, k), where k is the number of ones on the path so far, and memoize it. Prune when k > s or when the zeros so far (i + j + 1 - k) exceed s. At the last cell, succeed when k == s.
Complexity: O(m * n * (m + n)) time and space, since k is at most (m + n) / 2.
from functools import lru_cache
class Solution:
def isThereAPath(self, grid: List[List[int]]) -> bool:
@lru_cache(None)
def dfs(i, j, k):
if i >= m or j >= n:
return False
k += grid[i][j]
if k > s or i + j + 1 - k > s:
return False
if i == m - 1 and j == n - 1:
return k == s
return dfs(i + 1, j, k) or dfs(i, j + 1, k)
m, n = len(grid), len(grid[0])
s = m + n - 1
if s & 1:
return False
s >>= 1
return dfs(0, 0, 0)