[LeetCode] Check if There is a Path With Equal Number of 0's And 1's

2510. Check if There is a Path With Equal Number of 0’s And 1’s

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool isThereAPath(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
vector<vector<bitset<222>>> dp(n, vector<bitset<222>>(m));
dp[0][0][111] = 1;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(i) dp[i][j] |= dp[i-1][j];
if(j) dp[i][j] |= dp[i][j-1];
if(A[i][j]) dp[i][j]<<=1;
else dp[i][j] >>=1;
}
}
return dp[n-1][m-1][111];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/31/PS/LeetCode/check-if-there-is-a-path-with-equal-number-of-0s-and-1s/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.