Count Paths With the Given XOR Value Problem
Description
LeetCode Problem 3393.
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
XORof 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.
Example 1:
Input: grid = [[2, 1, 5], [7, 10, 0], [12, 6, 4]], k = 11
Output: 3
Explanation:
The 3 paths are:
- (0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2)
- (0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2)
- (0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)
Example 2:
Input: grid = [[1, 3, 3, 3], [0, 3, 3, 2], [3, 0, 1, 1]], k = 2
Output: 5
Explanation:
The 5 paths are:
- (0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2) → (2, 3)
- (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → (2, 3)
- (0, 0) → (1, 0) → (1, 1) → (1, 2) → (1, 3) → (2, 3)
- (0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2) → (2, 3)
- (0, 0) → (0, 1) → (0, 2) → (1, 2) → (2, 2) → (2, 3)
Example 3:
Input: grid = [[1, 1, 1, 2], [3, 0, 3, 2], [3, 0, 2, 2]], k = 10
Output: 0
Constraints:
1 <= m == grid.length <= 3001 <= n == grid[r].length <= 3000 <= grid[r][c] < 160 <= k < 16
Solution
Approach: Dynamic programming over the XOR value
Since every value is below 16, the XOR of any path is also below 16. Let f[i][j][x] be the number of paths from the top-left corner to cell (i, j) whose XOR is x. A path reaches (i, j) from above or from the left, and then its XOR changes from y to y ^ grid[i][j], so
f[i][j][x ^ grid[i][j]] = f[i - 1][j][x] + f[i][j - 1][x]
with f[0][0][grid[0][0]] = 1. The answer is f[m - 1][n - 1][k] modulo 10^9 + 7. Only the previous row is needed, so the table can be rolled to one row.
Complexity: Time O(m * n * 16), space O(n * 16).
class Solution:
def countPathsWithXorValue(self, grid: List[List[int]], k: int) -> int:
MOD = 10**9 + 7
m, n = len(grid), len(grid[0])
# f[j][x]: number of paths from the top-left corner to the current row's cell j with XOR x
f = [[0] * 16 for _ in range(n)]
for i in range(m):
for j in range(n):
cur = [0] * 16
if i == 0 and j == 0:
cur[grid[0][0]] = 1
else:
up = f[j]
lf = f[j - 1] if j > 0 else None
v = grid[i][j]
for x in range(16):
c = (up[x] if i > 0 else 0) + (lf[x] if lf else 0)
if c:
cur[x ^ v] = (cur[x ^ v] + c) % MOD
f[j] = cur
return f[n - 1][k] % MOD