[LeetCode] Minimum Moves to Get a Peaceful Board

3189. Minimum Moves to Get a Peaceful Board

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int minMoves(vector<vector<int>>& A) {
vector<int> s1, s2;
for(int i = 0; i < A.size(); i++) {
s1.push_back(A[i][0]);
s2.push_back(A[i][1]);
}
sort(begin(s1), end(s1));
sort(begin(s2), end(s2));
int res = 0;
for(int i = 0; i < A.size(); i++) {
res += abs(i - s1[i]) + abs(i - s2[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/26/PS/LeetCode/minimum-moves-to-get-a-peaceful-board/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.