979. Minimum Moves to Get a Peaceful Board

Given a 2D array rooks of length n, where rooks[i] = [xi, yi] represents the position of a rook on an n x n chessboard. The task is to move the rooks 1 cell at a time vertically or horizontally (to an adjacent cell) such that the board becomes peaceful. Determine the minimum number of moves required to make the board peaceful.

A peaceful board is one where each row and each column contains exactly one rook. A rook can move one cell at a time in a horizontal or vertical direction. At no point can two rooks occupy the same cell.

Example 1:

Input: rooks = [[0,2],[2,2],[2,1]]

Output: 3

Explanation:

The rooks are initially positioned incorrectly. The optimal moves are:

Move the rook at (0,2) to (0,1).

Move the rook at (2,2) to (1,2).

Move the rook at (2,1) to (2,0).

Now, the board is peaceful, and the total moves = 3.

Example 2:

Input: rooks = [[1,1],[1,3],[2,3],[3,2]]

Output: 4

Explanation:

An optimal way to make the board peaceful takes 4 moves.

Now Your Turn!

Pick the correct output for the given input

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

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n == rooks.length <= 500
  • 0 <= xi, yi <= n - 1
  • No two rooks start in the same cell.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minMoves(vector<vector<int>>& rooks) {
}
};
Test Case

Input:

Rooks