Ctrl K

One Rook per Line

Medium
An n × n board holds n rooks: rooks[i] = [row, col] is the square of rook i (0-indexed). In one move any rook can step to a side-adjacent square. Two rooks may never share a square. The board is peaceful when every row and every column contains exactly one rook. Return the minimum number of moves to make the board peaceful.
Example 1
rooks=[[0, 1], [0, 2], [2, 2]] → 3

Move the rook from (0, 2) down to (1, 2), then the rook from (2, 2) left to (2, 1) and again to (2, 0). Rows 0, 1, 2 and columns 1, 2, 0 are each used once: 3 moves.

Example 2
rooks=[[1, 0], [0, 1]] → 0

The board is already peaceful.

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

All rooks are in row 2: lift one by one row and another by two rows, 3 moves.

Constraints
  • 1 ≤ n = len(rooks) ≤ 500
  • 0 ≤ row, col ≤ n - 1
  • No two rooks share a square
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMost Snacks on a Budget MediumStrength of the Weaker Partner EasyScooters to Chargers EasyBiggest Number From Pieces MediumStudios for Recording Sessions Medium
loading Python…
Input
rooks=[[0, 1], [0, 2], [2, 2]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 101 tests on the server, hidden ones included.