[LeetCode] Minimum XOR Path in a Grid

3882. Minimum XOR Path in a Grid

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int minCost(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
unordered_set<int> dp[n][m];
dp[0][0].insert(grid[0][0]);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(i) {
for(auto& x : dp[i-1][j]) dp[i][j].insert(x ^ grid[i][j]);
}
if(j) {
for(auto& x : dp[i][j-1]) dp[i][j].insert(x ^ grid[i][j]);
}
}
}
return *min_element(begin(dp[n-1][m-1]), end(dp[n-1][m-1]));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-xor-path-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.