Problem
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 tok
.
Return the total number of such paths.
Since the answer can be very large, return the result modulo 10^9 + 7
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= m == grid.length <= 300
1 <= n == grid[r].length <= 300
0 <= grid[r][c] < 16
0 <= k < 16
Solution
Method 1 – Dynamic Programming (DP) with XOR State
Intuition
Since the grid values and k are small (0-15), we can use DP to track the number of ways to reach each cell with a given XOR value. For each cell, the number of ways to reach it with XOR x is the sum of the ways to reach the cell above and the cell to the left with XOR (x ^ grid[i][j]).
Approach
- Let
dp[i][j][x]
be the number of ways to reach cell (i, j) with XOR value x. - Initialize
dp[0][0][grid[0][0]] = 1
. - For each cell (i, j), for each possible XOR value x (0 to 15):
- If i > 0, add
dp[i-1][j][x ^ grid[i][j]]
todp[i][j][x]
. - If j > 0, add
dp[i][j-1][x ^ grid[i][j]]
todp[i][j][x]
.
- If i > 0, add
- The answer is
dp[m-1][n-1][k]
. - Return the answer modulo 10^9+7.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n * 16)
, since we process each cell and each possible XOR value. - 🧺 Space complexity:
O(m * n * 16)
, for the DP table.