Minimum Moves to Get a Peaceful Board

Updated on 15 July, 2025
Minimum Moves to Get a Peaceful Board header image

Problem Statement

In this problem, you're provided with a 2D array named rooks, representing positions of rooks on an n x n chessboard. Each entry in the array rooks[i] consists of two integers [xi, yi], denoting the row and column positions of a rook. Your goal is to reposition these rooks such that no two rooks are in the same row or column. This condition is what defines a board as "peaceful."

The challenge is to determine the minimum number of moves to achieve a peaceful board by moving any rook one cell at a time either vertically or horizontally. It is important to note that no two rooks can occupy the same cell at any time during the repositioning process.

Examples

Example 1

Input:

rooks = [[0,0],[1,0],[1,1]]

Output:

3

Explanation:

Move rook at [1,0] to [2,0] (1 move).
Move rook at [1,1] to [1,2] (1 move).
Move rook at [2,0] to [2,2] (1 move).
Total moves = 3.

Example 2

Input:

rooks = [[0,0],[0,1],[0,2],[0,3]]

Output:

6

Explanation:

Move rook at [0,1] to [1,1] (1 move).
Move rook at [0,2] to [2,2] (2 moves).
Move rook at [0,3] to [3,3] (3 moves).
Total moves = 6.

Constraints

  • 1 <= n == rooks.length <= 500
  • 0 <= xi, yi <= n - 1
  • The input is generated such that there are no 2 rooks in the same cell.

Approach and Intuition

To solve the problem of getting all rooks to a peaceful state, it's pivotal to understand the movement mechanics and the desired end state:

  1. Begin by noting the current positions of all rooks on the board using the given positions in the rooks array.
  2. The goal is to distribute the rooks such that each row and each column contains exactly one rook. This distribution ensures that no two rooks can threaten each other based on chess rules for rooks.
  3. The optimal strategy involves finding a unique row-column assignment for each rook such that the total Manhattan distance moved is minimized.

A Hungarian Algorithm (minimum-cost bipartite matching) is an efficient approach here:

  • Treat each current rook position as a "worker" and target peaceful positions (i.e., permutations of row and column indices) as "jobs."
  • Calculate the cost (Manhattan distance) for each worker-job pair.
  • Use the algorithm to assign each rook a unique target such that total movement cost is minimized.

This problem is fundamentally an assignment optimization problem over a bipartite graph where each assignment cost is the distance to be moved.

Solutions

  • C++
cpp
class Solution {
public:
    int calculateMinMoves(vector<vector<int>>& pieces) {
        int totalMoves = 0;
    
        vector<int> rowCount(pieces.size(), 0);
        vector<int> colCount(pieces.size(), 0);
        for (int i = 0; i < pieces.size(); i++) {
            rowCount[pieces[i][0]]++;
            colCount[pieces[i][1]]++;
        }
    
        int movesNeededRow = 0, movesNeededCol = 0;
        for (int i = 0; i < pieces.size(); i++) {
            movesNeededRow += rowCount[i] - 1;
            movesNeededCol += colCount[i] - 1;
    
            totalMoves += abs(movesNeededRow) + abs(movesNeededCol);
        }
    
        return totalMoves;
    }
};

The given C++ code provides a solution for finding the minimum number of moves required to rearrange pieces on a board in a manner where no two pieces are on the same row or column. The calculateMinMoves function is capable of computing this by using a step-by-step method, which involves counting the distribution of pieces across both rows and columns, and then calculating the required moves to solve any conflicts.

  • Start by initializing a counter, totalMoves, to keep track of the total number of moves needed.
  • Two vectors, rowCount and colCount, are declared to record the number of pieces in each row and column, respectively.
  • The first loop through the board updates these counts for every piece’s position.
  • Subsequent calculations determine the excess count of pieces in each row and column that would need to be moved to achieve one piece per row and column.
  • This is calculated using the difference from 1 (as one piece is allowed per row and column) for each row and column.
  • Accumulate the absolute values of these differences into totalMoves, which gives the total adjustments needed across the board.
  • Finally, return totalMoves, which will be the minimum number of moves needed to arrange the board peacefully with no two pieces sharing the same row or column.
  • Java
java
class Solution {
    
    public int minimumMoves(int[][] pieces) {
        int moves = 0;
    
        // Counting the rooks in rows and columns
        int[] rows = new int[pieces.length];
        int[] columns = new int[pieces.length];
        for (int i = 0; i < pieces.length; i++) {
            rows[pieces[i][0]]++;
            columns[pieces[i][1]]++;
        }
    
        int movesForRow = 0, movesForColumn = 0;
        for (int i = 0; i < pieces.length; i++) {
            // Calculate the exceeding number of rooks per row/column over one
            movesForRow += rows[i] - 1;
            movesForColumn += columns[i] - 1;
    
            // Total moves needed for aligning rows and columns correctly
            moves += Math.abs(movesForRow) + Math.abs(movesForColumn);
        }
    
        return moves;
    }
}

To solve the problem of finding the minimum moves required to achieve a peaceful board configuration, the given Java code implements a strategic counting solution. The method minimumMoves() takes a two-dimensional array pieces as input, representing the positions of rooks on an initially empty board.

The process comprises the following steps:

  1. Initialize moves to zero, which will eventually hold the total number of moves required.
  2. Set up two arrays, rows and columns, to store the count of rooks in each row and column, respectively.
  3. Populate these arrays by iterating over each piece's placement, incrementing the respective row and column indices.
  4. Initialize variables movesForRow and movesForColumn to handle the cumulative calculation of necessary adjustments in rows and columns.
  5. Loop through each row and column:
    • Compute the excess rooks (beyond one rook per row or column) that need to be relocated.
    • Accumulate adjustments, considering both the overages in rows and columns, by adding the absolute differences of the movements needed to balance rooks to one per row and column.
  6. Return the total calculated moves.

This solution effectively tracks and adjusts the distribution of rooks to ensure that no two rooks share a row or a column, using a straightforward counting and accumulation strategy without requiring complex data structures or algorithms. Adjusting the position of rooks in this manner minimizes the number of moves required to reach a non-conflicting state on the board.

  • Python
python
class Solution:
    def calculateMinMoves(self, rookPositions):
        movesNeeded = 0
    
        # Track rooks in rows and columns using counters.
        rowCounters = [0] * len(rookPositions)
        colCounters = [0] * len(rookPositions)
        for position in rookPositions:
            rowCounters[position[0]] += 1
            colCounters[position[1]] += 1
    
        rowMoves = 0
        colMoves = 0
        for idx in range(len(rookPositions)):
            # Compute the extra or missing rooks in each dimension.
            rowMoves += rowCounters[idx] - 1
            colMoves += colCounters[idx] - 1
    
            # Calculate the moves needed to fix each row and column.
            movesNeeded += abs(rowMoves) + abs(colMoves)
    
        return movesNeeded

The Python script provided tackles the problem of calculating the minimum number of moves required to adjust the positions of rooks on a chessboard to achieve a peaceful board state, where all rooks in each row and column are correctly aligned. This script implements a method called calculateMinMoves which takes a list of rookPositions indicating the current position of each rook.

  • First, arrays rowCounters and colCounters count how many rooks are present in each row and column correspondingly, initializing them based on the size of rookPositions.
  • A loop iterates over the positions, increasing the corresponding counters for the row and column of each rook to represent their presence in these dimensions.
  • To calculate the moves, it employs another loop. During this loop, for each index, the script computes the discrepancy in the number of rooks in each row and column by subtracting one (the ideal number of rooks per row/column) and accumulates the absolute values of these discrepancies.
  • The script finally returns movesNeeded, which sums the required movements needed to rectify the discrepancies for each row and column, thus providing the minimum moves to achieve a peaceful board setup.

This solution efficiently utilizes counting arrays and simple mathematical operations to derive the solution, ensuring that the computation scales well even for larger boards. Make sure the provided rookPositions are correctly formatted and the indexes are within the board limits to prevent errors in computation.

Comments

No comments yet.