LeetCode-in-Java

3283. Maximum Number of Moves to Kill All Pawns

Hard

There is a 50 x 50 chessboard with one knight and some pawns on it. You are given two integers kx and ky where (kx, ky) denotes the position of the knight, and a 2D array positions where positions[i] = [xi, yi] denotes the position of the pawns on the chessboard.

Alice and Bob play a turn-based game, where Alice goes first. In each player’s turn:

Alice is trying to maximize the sum of the number of moves made by both players until there are no more pawns on the board, whereas Bob tries to minimize them.

Return the maximum total number of moves made during the game that Alice can achieve, assuming both players play optimally.

Note that in one move, a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.

Example 1:

Input: kx = 1, ky = 1, positions = [[0,0]]

Output: 4

Explanation:

The knight takes 4 moves to reach the pawn at (0, 0).

Example 2:

Input: kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]]

Output: 8

Explanation:

Example 3:

Input: kx = 0, ky = 0, positions = [[1,2],[2,4]]

Output: 3

Explanation:

Constraints:

Solution

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    private static final int[][] KNIGHT_MOVES = {
        {-2, -1}, {-2, 1}, {-1, -2}, {-1, 2},
        {1, -2}, {1, 2}, {2, -1}, {2, 1}
    };
    private int[][] distances;
    private Integer[][] memo;

    public int maxMoves(int kx, int ky, int[][] positions) {
        int n = positions.length;
        distances = new int[n + 1][n + 1];
        memo = new Integer[n + 1][1 << n];
        // Calculate distances between all pairs of positions (including knight's initial position)
        for (int i = 0; i < n; i++) {
            distances[n][i] = calculateMoves(kx, ky, positions[i][0], positions[i][1]);
            for (int j = i + 1; j < n; j++) {
                int dist =
                        calculateMoves(
                                positions[i][0], positions[i][1], positions[j][0], positions[j][1]);
                distances[i][j] = distances[j][i] = dist;
            }
        }
        return minimax(n, (1 << n) - 1, true);
    }

    private int minimax(int lastPos, int remainingPawns, boolean isAlice) {
        if (remainingPawns == 0) {
            return 0;
        }
        if (memo[lastPos][remainingPawns] != null) {
            return memo[lastPos][remainingPawns];
        }
        int result = isAlice ? 0 : Integer.MAX_VALUE;
        for (int i = 0; i < distances.length - 1; i++) {
            if ((remainingPawns & (1 << i)) != 0) {
                int newRemainingPawns = remainingPawns & ~(1 << i);
                int moveValue = distances[lastPos][i] + minimax(i, newRemainingPawns, !isAlice);

                if (isAlice) {
                    result = Math.max(result, moveValue);
                } else {
                    result = Math.min(result, moveValue);
                }
            }
        }
        memo[lastPos][remainingPawns] = result;
        return result;
    }

    private int calculateMoves(int x1, int y1, int x2, int y2) {
        if (x1 == x2 && y1 == y2) {
            return 0;
        }
        boolean[][] visited = new boolean[50][50];
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[] {x1, y1, 0});
        visited[x1][y1] = true;
        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int x = current[0];
            int y = current[1];
            int moves = current[2];
            for (int[] move : KNIGHT_MOVES) {
                int nx = x + move[0];
                int ny = y + move[1];
                if (nx == x2 && ny == y2) {
                    return moves + 1;
                }
                if (nx >= 0 && nx < 50 && ny >= 0 && ny < 50 && !visited[nx][ny]) {
                    queue.offer(new int[] {nx, ny, moves + 1});
                    visited[nx][ny] = true;
                }
            }
        }
        // Should never reach here if input is valid
        return -1;
    }
}