2510. Check if There is a Path With Equal Number of 0's And 1's π
Description
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.
Solutions
Solution 1: Memoization Search
Thinking
Paths from the top-left to the bottom-right only move right or down, so their length is \(m+n-1\). An odd length cannot split equally between \(0\)s and \(1\)s. Full path enumeration is too large for \(m,n\le 100\).
The target is \(s=(m+n-1)/2\) ones (and the same number of zeros). State \((i,j,k)\) is position \((i,j)\) with \(k\) ones so far; prune when \(k\) or the zero count already exceeds \(s\). Memoization yields \(O(mn(m+n))\) states.
According to the problem description, we know that the number of 0s and 1s on the path from the top-left corner to the bottom-right corner is equal, and the total number is \(m + n - 1\), which means the number of 0s and 1s are both \((m + n - 1) / 2\).
Therefore, we can use memoization search, starting from the top-left corner and moving right or down until reaching the bottom-right corner, to check if the number of 0s and 1s on the path is equal.
The time complexity is \(O(m \times n \times (m + n))\). Here, \(m\) and \(n\) are the number of rows and columns of the matrix, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |

