Problem
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 anequal number of _0
_’ s and _1
’ s. Otherwise return
false
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 100
grid[i][j]
is either0
or1
.
Solution
Method 1 – Dynamic Programming with Balance Tracking
Intuition
We need to find a path from the top-left to the bottom-right of the grid such that the number of 0’s and 1’s is equal. Since we can only move right or down, and the path length is fixed, we can use dynamic programming to track the possible balances (difference between 1’s and 0’s) at each cell.
Reasoning
At each cell, the only information that matters is the current balance (number of 1’s minus number of 0’s) and the position. We can use a set to track all possible balances at each cell, propagating from the top-left to the bottom-right. If a balance of 0 is possible at the end, then a valid path exists.
Approach
- Let
m
andn
be the grid dimensions. The path length ism + n - 1
. - If the path length is odd, return false (cannot split evenly between 0’s and 1’s).
- Use a DP table where
dp[i][j]
is a set of possible balances at cell(i, j)
. - Initialize
dp[0][0]
with the balance at the starting cell. - For each cell, propagate possible balances from the top and left neighbors, updating the balance according to the current cell’s value.
- At the end, check if a balance of 0 is possible at the bottom-right cell.
Edge cases:
- Path length is odd: impossible.
- All 0’s or all 1’s: impossible.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n * k)
, wherek
is the number of possible balances (at mostm+n
), as we track all possible balances at each cell. - 🧺 Space complexity:
O(m * n * k)
, as we store possible balances for each cell.