Minimum Moves to Get a Peaceful Board - Problem

Given a 2D array rooks of length n, where rooks[i] = [xi, yi] indicates the position of a rook on an n x n chess board.

Your task is to move the rooks 1 cell at a time vertically or horizontally (to an adjacent cell) such that the board becomes peaceful.

A board is peaceful if there is exactly one rook in each row and each column.

Return the minimum number of moves required to get a peaceful board. Note that at no point can there be two rooks in the same cell.

Input & Output

Example 1 — Basic 3x3 Board
$ Input: rooks = [[0,0],[1,1],[2,5]]
Output: 3
💡 Note: Move rook at [2,5] to [2,2] taking 3 moves (5→4→3→2). Other rooks are already in valid positions for a peaceful board where each row and column has exactly one rook.
Example 2 — All Rooks in Same Row
$ Input: rooks = [[0,0],[0,1],[0,2]]
Output: 4
💡 Note: Current: all rooks in row 0. Need to spread to rows 0,1,2 and columns 0,1,2. Optimal assignment gives total Manhattan distance of 4 moves.
Example 3 — Already Peaceful
$ Input: rooks = [[0,0],[1,1]]
Output: 0
💡 Note: Board is already peaceful - each row (0,1) and each column (0,1) has exactly one rook. No moves needed.

Constraints

  • n == rooks.length
  • 1 ≤ n ≤ 100
  • rooks[i].length == 2
  • 0 ≤ xi, yi ≤ n - 1
  • All the positions of rooks are unique

Visualization

Tap to expand
Minimum Moves to Get a Peaceful BoardCurrent BoardPositions: [[0,0],[1,1],[2,5]]AlgorithmSort & MatchPeaceful BoardTarget: [[0,0],[1,1],[2,2]]Rook at [2,5] moves to [2,2] = 3 movesOutput: 3Each row and column must have exactly one rook
Understanding the Visualization
1
Input
Chess board with rooks in arbitrary positions
2
Process
Calculate minimum moves to make each row and column have exactly one rook
3
Output
Return the total minimum number of moves required
Key Takeaway
🎯 Key Insight: Sort row and column coordinates independently, then greedily match to minimize Manhattan distance
Asked in
Google 35 Amazon 28 Microsoft 22
25.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen