#3189
Medium Algorithms Minimum moves to get a peaceful board
Array Greedy Sorting Counting Sort
75.9% acceptance
Mar 31, 2026
61
13
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn min_moves(rooks: Vec<Vec<i32>>) -> i32 {
let n = rooks.len();
let mut rows: Vec<i32> = rooks.iter().map(|r| r[0]).collect();
let mut cols: Vec<i32> = rooks.iter().map(|r| r[1]).collect();
rows.sort_unstable();
cols.sort_unstable();
let mut total = 0;
for i in 0..n {
total += (rows[i] - i as i32).abs() + (cols[i] - i as i32).abs();
}
total
}
}