Problem Description
Given an n x n chessboard with n rooks placed such that each rook's location is given by rooks[i] = [x_i, y_i] (with no two rooks at the same cell), the goal is to move the rooks one cell at a time (vertically or horizontally) so that the board becomes peaceful. A peaceful board means that every row and every column contains exactly one rook. Moves must be planned so that at no point do two rooks share the same cell. Return the minimum number of moves needed to achieve a peaceful configuration.
Key Insights
- The problem can be separated into two independent tasks: assigning unique rows and unique columns to the rooks.
- Since rooks move one cell at a time, the cost to move a rook from row x to row r is |x - r|, and similarly for columns.
- To minimize the total moves, sort the list of current row indices and match them to the target rows (0 to n-1). Repeat the process for column indices.
- The sum of the absolute differences for rows plus the sum for columns gives the minimum number of moves.
- Sorting naturally aligns the positions in an optimal manner due to the properties of the absolute difference metric.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting of the rows and columns. Space Complexity: O(n) for storing the sorted row and column lists.
Solution
We start by extracting the row and column coordinates of the rooks. Since each move cost is the absolute difference in positions and the moves in rows and columns are independent, we solve the row moves and column moves individually. Sort the list of current row coordinates and assign them optimally to target rows 0, 1, ..., n-1. Similarly, sort the column coordinates and assign them to target columns. The sum of these differences is the answer.
This approach uses sorting (for optimal pairing) and simply iterates the lists to compute the absolute differences, achieving both clarity and efficiency.