Back to October Back to Year 2026
MEDIUM 28 Oct 2026 View on LeetCode

3882. Minimum XOR Path in a Grid

</> Solution

/**
 * Problem: LeetCode 3882 - Minimum XOR Path in a Grid
 * Difficulty: Medium
 * Language: Java
 * Author: CodeByTushu
 */
class Solution {
    public int minCost(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        boolean[][][] dp = new boolean[m][n][1024];
        dp[0][0][grid[0][0]] = true;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) continue;
                int val = grid[i][j];
                for (int x = 0; x < 1024; x++) {
                    boolean reachable = false;
                    if (i > 0 && dp[i - 1][j][x]) reachable = true;
                    if (j > 0 && dp[i][j - 1][x]) reachable = true;
                    if (reachable) dp[i][j][x ^ val] = true;
                }
            }
        }
        for (int x = 0; x < 1024; x++) {
            if (dp[m - 1][n - 1][x]) return x;
        }
        return -1;
    }
}

TIME COMPLEXITY

O(m * n * 1024)

SPACE COMPLEXITY

O(m * n * 1024)

TOPICS

Array Bit Manipulation Dynamic Programming Matrix