Minimum XOR Path in a Grid Problem
Description
LeetCode Problem 3882.
You are given a 2D integer array grid of size m * n.
You start at the top-left cell (0, 0) and want to reach the bottom-right cell (m - 1, n - 1).
At each step, you may move either right or down.
The cost of a path is defined as the bitwise XOR of all the values in the cells along that path, including the start and end cells.
Return the minimum possible XOR value among all valid paths from (0, 0) to (m - 1, n - 1).
Example 1:
Input: grid = [[1,2],[3,4]]
Output: 6
Explanation:
There are two valid paths:
- (0, 0) → (0, 1) → (1, 1) with XOR: 1 XOR 2 XOR 4 = 7
- (0, 0) → (1, 0) → (1, 1) with XOR: 1 XOR 3 XOR 4 = 6
The minimum XOR value among all valid paths is 6.
Example 2:
Input: grid = [[6,7],[5,8]]
Output: 9
Explanation:
There are two valid paths:
- (0, 0) → (0, 1) → (1, 1) with XOR: 6 XOR 7 XOR 8 = 9
- (0, 0) → (1, 0) → (1, 1) with XOR: 6 XOR 5 XOR 8 = 11
The minimum XOR value among all valid paths is 9.
Example 3:
Input: grid = [[2,7,5]]
Output: 0
Explanation:
There is only one valid path:
- (0, 0) → (0, 1) → (0, 2) with XOR: 2 XOR 7 XOR 5 = 0
The XOR value of this path is 0, which is the minimum possible.
Constraints:
1 <= m == grid.length <= 10001 <= n == grid[i].length <= 1000m * n <= 10000 <= grid[i][j] <= 1023
Solution
Approach: Dynamic Programming over XOR Values
Let f[i][j][k] be true if some path from (0, 0) to cell (i, j) has XOR exactly k.
Cell values are at most 1023, so every path XOR is below 2^b, where b is the bit length of the largest value in the grid (mx = 2^b <= 1024). Start with f[0][0][grid[0][0]] = true.
Go through the cells in row-major order. For a cell with value x that is not the start, f[i][j][k] is true if f[i - 1][j][k ^ x] is true (arriving from above) or f[i][j - 1][k ^ x] is true (arriving from the left), since the XOR before entering the cell must be k ^ x. Moves go only right or down, so both neighbours are already computed.
The answer is the smallest k with f[m - 1][n - 1][k] true; one always exists because a path exists.
Complexity: time O(m * n * mx), space O(m * n * mx), with mx <= 1024 and m * n <= 1000.
class Solution:
def minCost(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
mx = 1 << (max(max(row) for row in grid)).bit_length()
f = [[[False] * mx for _ in range(n)] for _ in range(m)]
f[0][0][grid[0][0]] = True
for i, row in enumerate(grid):
for j, x in enumerate(row):
if i > 0 or j > 0:
for k in range(mx):
if i > 0 and f[i - 1][j][k ^ x]:
f[i][j][k] = True
if j > 0 and f[i][j - 1][k ^ x]:
f[i][j][k] = True
return next(k for k in range(mx) if f[m - 1][n - 1][k])