const dr = [1, -1, 0, 0, 0];
const dc = [0, 0, 1, -1, 0];
function rotate(clock, rt, n, r, c) {
for (let d = 0; d < 5; d++) {
let nr = r + dr[d];
let nc = c + dc[d];
if (0 <= nr && nr < n && 0 <= nc && nc < n) {
clock[nr][nc] = (clock[nr][nc] + rt) % 4;
}
}
}
function solution(clockHands) {
let answer = Infinity;
const n = clockHands.length;
for (let firstRowCase = 0; firstRowCase < 4 ** n; firstRowCase++) {
const copied = JSON.parse(JSON.stringify(clockHands));
let rotateCnt = 0;
for (let j = 0; j < n; j++) {
const rt = (firstRowCase % 4 ** (j + 1) / 4 ** j) | 0;
if (rt === 0) {
continue
}
rotateCnt += rt;
rotate(copied, rt, n, 0, j);
};
for (let r = 1; r < n; r++) {
for (let c = 0; c < n; c++) {
const upperPoint = copied[r-1][c];
if (upperPoint !== 0) {
const rt = 4 - upperPoint;
rotate(copied, rt, n, r, c);
rotateCnt += rt
}
}
};
const sum = copied[n-1].reduce((acc, curr) => acc + curr, 0);
if (sum === 0) {
answer = Math.min(answer, rotateCnt);
}
}
return answer;
}