#3393
Count Paths With the Given XOR Value
MediumArrayDynamic ProgrammingBit ManipulationMatrixDynamic ProgrammingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^(m+n)) | O(m * n * maxXOR) |
| Space | O(m+n) | O(m * n * maxXOR) |
💡
Intuition
Time O(m * n * maxXOR)Space O(m * n * maxXOR)
We can use dynamic programming to store the number of ways to reach each cell with a specific XOR value. This avoids recalculating paths and significantly reduces the number of computations.
⚙️
Algorithm
3 steps- 1Step 1: Create a 3D DP array where dp[i][j][x] represents the number of ways to reach cell (i, j) with XOR value x.
- 2Step 2: Initialize dp[0][0][grid[0][0]] to 1 since there's one way to start at the top-left corner.
- 3Step 3: Iterate through each cell and update the DP table based on possible moves (down and right) while maintaining the XOR value.
solution.py16 lines
1def countPaths(grid, k):
2 from collections import defaultdict
3 m, n = len(grid), len(grid[0])
4 dp = defaultdict(int)
5 dp[(0, 0, grid[0][0])] = 1
6 mod = 10**9 + 7
7 for i in range(m):
8 for j in range(n):
9 for x in list(dp.keys()):
10 if x[0] == i and x[1] == j:
11 count = dp[x]
12 if i + 1 < m:
13 dp[(i + 1, j, x[2] ^ grid[i + 1][j])] += count
14 if j + 1 < n:
15 dp[(i, j + 1, x[2] ^ grid[i][j + 1])] += count
16 return sum(dp[(m - 1, n - 1, x)] for x in dp if x[0] == m - 1 and x[1] == n - 1 and x[2] == k) % modℹ
Complexity note: The time complexity is based on the number of cells and the maximum possible XOR values we might encounter. The space complexity is due to storing results for each cell and XOR value.
- 1Dynamic programming can significantly reduce the time complexity compared to brute force.
- 2Understanding how XOR works is crucial for solving this problem effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.