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.
To get a peaceful board, we need to assign each rook to a unique row and column. This is equivalent to finding a minimum cost matching between the current positions and the target positions (one rook per row and column). The cost is the Manhattan distance for each assignment.
classSolution {
public:int minMovesToPeacefulBoard(vector<vector<int>>& rooks) {
int n = rooks.size();
vector<int> xs, ys;
for (auto& r : rooks) {
xs.push_back(r[0]);
ys.push_back(r[1]);
}
sort(xs.begin(), xs.end());
sort(ys.begin(), ys.end());
int ans =0;
for (int i =0; i < n; ++i) {
ans += abs(xs[i] - i);
ans += abs(ys[i] - i);
}
return ans;
}
};
classSolution {
publicintminMovesToPeacefulBoard(int[][] rooks) {
int n = rooks.length;
int[] xs =newint[n], ys =newint[n];
for (int i = 0; i < n; i++) {
xs[i]= rooks[i][0];
ys[i]= rooks[i][1];
}
Arrays.sort(xs);
Arrays.sort(ys);
int ans = 0;
for (int i = 0; i < n; i++) {
ans += Math.abs(xs[i]- i) + Math.abs(ys[i]- i);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funminMovesToPeacefulBoard(rooks: Array<IntArray>): Int {
val n = rooks.size
val xs = IntArray(n) { rooks[it][0] }
val ys = IntArray(n) { rooks[it][1] }
xs.sort()
ys.sort()
var ans = 0for (i in0 until n) {
ans += kotlin.math.abs(xs[i] - i) + kotlin.math.abs(ys[i] - i)
}
return ans
}
}
1
2
3
4
5
defmin_moves_to_peaceful_board(rooks: list[list[int]]) -> int:
n = len(rooks)
xs = sorted(r[0] for r in rooks)
ys = sorted(r[1] for r in rooks)
return sum(abs(xs[i] - i) + abs(ys[i] - i) for i in range(n))
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnmin_moves_to_peaceful_board(rooks: Vec<Vec<i32>>) -> i32 {
let n = rooks.len();
letmut xs: Vec<i32>= rooks.iter().map(|r| r[0]).collect();
letmut ys: Vec<i32>= rooks.iter().map(|r| r[1]).collect();
xs.sort(); ys.sort();
letmut ans =0;
for i in0..n {
ans += (xs[i] - i asi32).abs() + (ys[i] - i asi32).abs();
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
minMovesToPeacefulBoard(rooks: number[][]):number {
constn=rooks.length;
constxs=rooks.map(r=>r[0]).sort((a, b) =>a-b);
constys=rooks.map(r=>r[1]).sort((a, b) =>a-b);
letans=0;
for (leti=0; i<n; i++) {
ans+= Math.abs(xs[i] -i) + Math.abs(ys[i] -i);
}
returnans;
}
}