LeetCode in Kotlin

3882. Minimum XOR Path in a Grid

Medium

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:

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:

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:

The XOR value of this path is 0, which is the minimum possible.

Constraints:

Solution

import kotlin.math.min

class Solution {
    private var ans = 0
    private lateinit var memo: Array<Array<BooleanArray>>

    fun minCost(grid: Array<IntArray>): Int {
        ans = Int.MAX_VALUE
        memo = Array<Array<BooleanArray>>(grid.size) { Array<BooleanArray>(grid[0].size) { BooleanArray(1024) } }
        dfs(grid, 0, 0, 0, grid.size, grid[0].size)
        return ans
    }

    private fun dfs(grid: Array<IntArray>, i: Int, j: Int, xor: Int, m: Int, n: Int) {
        var xor = xor
        xor = xor xor grid[i][j]
        if (ans == 0) {
            return
        }
        if (memo[i][j][xor]) {
            return
        }
        memo[i][j][xor] = true
        if (i == m - 1 && j == n - 1) {
            ans = min(ans, xor)
            return
        }
        if (i + 1 < m) {
            dfs(grid, i + 1, j, xor, m, n)
        }
        if (j + 1 < n) {
            dfs(grid, i, j + 1, xor, m, n)
        }
    }
}