[LeetCode] Count Paths With the Given XOR Value

3393. Count Paths With the Given XOR Value

You are given a 2D integer array grid with size m x n. You are also given an integer k.

Your task is to calculate the number of paths you can take from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1) satisfying the following constraints:

  • You can either move to the right or down. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j) if the target cell exists.
  • The XOR of all the numbers on the path must be equal to k.

Return the total number of such paths.

Since the answer can be very large, return the result modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int countPathsWithXorValue(vector<vector<int>>& grid, int k) {
long long n = grid.size(), m = grid[0].size(), mod = 1e9 + 7;
vector<vector<vector<long long>>> dp(n, vector<vector<long long>>(m, vector<long long>(64)));
dp[0][0][grid[0][0]] = 1;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int k = 0; k < 64; k++) {
if(i + 1 < n) {
dp[i+1][j][k ^ grid[i+1][j]] = (dp[i+1][j][k ^ grid[i+1][j]] + dp[i][j][k]) % mod;
}
if(j + 1 < m) {
dp[i][j+1][k ^ grid[i][j+1]] = (dp[i][j+1][k ^ grid[i][j+1]] + dp[i][j][k]) % mod;
}
}
}
}
return dp[n-1][m-1][k];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/22/PS/LeetCode/count-paths-with-the-given-xor-value/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.