Minimum Moves to Get a Peaceful Board Problem
Description
LeetCode Problem 3189.
Given a 2D array rooks of length n, where rooks[i] = [x_i, y_i] 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.
Example 1:
Input: rooks = [[0,0],[1,0],[1,1]]
Output: 3
Explanation:

Example 2:
Input: rooks = [[0,0],[0,1],[0,2],[0,3]]
Output: 6
Explanation:

Constraints:
1 <= n == rooks.length <= 5000 <= x_i, y_i <= n - 1- The input is generated such that there are no 2 rooks in the same cell.
Solution
Approach: Greedy
Rows and columns are independent: the rooks need distinct rows and distinct columns, so each row index and each column index must end up used exactly once. Sort the rooks by x and send the i-th rook to row i, summing the distances; then sort by y and do the same for columns. The total of both sums is the answer.
Complexity: O(n log n) time and O(log n) space, where n is the number of rooks.
class Solution:
def minMoves(self, rooks: List[List[int]]) -> int:
rooks.sort()
ans = sum(abs(x - i) for i, (x, _) in enumerate(rooks))
rooks.sort(key=lambda x: x[1])
ans += sum(abs(y - j) for j, (_, y) in enumerate(rooks))
return ans