1. Description
Given an m x n integer matrix grid, travel from (0,0) to (m - 1,n - 1), moving only one cell right or down at each step.
A path’s cost is the bitwise XOR of every cell value it visits, including both endpoints.
Return the smallest cost achievable by any such path.
2. Example
Example 1
Input: grid = [[1,2],[3,4]]
Output: 6
Explanation: Moving right then down gives 1 XOR 2 XOR 4 = 7. Moving down then right gives 1 XOR 3 XOR 4 = 6, which is smaller.
Example 2
Input: grid = [[6,7],[5,8]]
Output: 9
Explanation: The two paths have costs 6 XOR 7 XOR 8 = 9 and 6 XOR 5 XOR 8 = 11. The minimum is 9.
Example 3
Input: grid = [[2,7,5]]
Output: 0
Explanation: The single row permits just one path, whose cost is 2 XOR 7 XOR 5 = 0.
3. Constraints
- 1 <= m == grid.length <= 1000
- 1 <= n == grid[i].length <= 1000
- m * n <= 1000
- 0 <= grid[i][j] <= 1023
4. Solutions
Dynamic Programming
m = grid.size(), n = grid.front().size(), U = 1024
Time complexity: O(mnU)
Space complexity: O(nU)
| |