Problem Description
Given an m x n binary matrix, determine if there exists a valid path from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1) that only moves either down or right and visits an equal number of 0's and 1's. A valid path must satisfy that the total number of cells visited (which is m+n-1) contains half 0’s and half 1’s.
Key Insights
- The only possible moves are down and right.
- The length of any valid path is fixed to m+n-1. For a path to have an equal number of 0's and 1's, m+n-1 must be even.
- Use DFS (or DP) with memoization to explore all possible paths while tracking the difference between the count of zeros and ones.
- The state is defined by the current position (row, col) and the difference (count0 - count1) so far.
- A valid end state is reached when (row, col) is the bottom-right cell and the difference is zero.
Space and Time Complexity
Time Complexity: O(m * n * D) where D is the range of possible differences (bounded by the path length, roughly m+n).
Space Complexity: O(m * n * D) for the recursion stack and memoization.
Solution
We use a recursive DFS approach with memoization to keep track of states we have already processed. Each state is represented by (row, col, currentDifference) where currentDifference is the difference between the number of 0's and 1's encountered so far (with 0 incrementing the difference and 1 decrementing it). We start from the top-left corner and at every step move either right or down. When reaching the bottom-right cell, we check if the difference is zero.
Before starting, a quick check on the parity of (m+n-1) can quickly rule out the possibility of a valid path if it is odd.