I’m rotating an NxN matrix 90 degrees clockwise in place. For some inputs, values get duplicated and others disappear. I suspect my loop bounds or assignment order is wrong, but I can’t spot it.
function rotate(m) {
const n = m.length;
for (let layer = 0; layer < n / 2; layer++) {
for (let i = layer; i < n - layer - 1; i++) {
const top = m[layer][i];
m[layer][i] = m[n - 1 - i][layer];
m[n - 1 - i][layer] = m[n - 1 - layer][n - 1 - i];
m[n - 1 - layer][n - 1 - i] = m[i][n - 1 - layer];
m[i][n - 1 - layer] = m[layer][i];
}
}
}
What exactly is being overwritten here, and what’s the minimal fix?
BayMax