In place: transpose + reverse
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function (matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
transpose(matrix, i, j);
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < Math.floor(n / 2); j++) {
reverse(matrix, i, j);
}
}
};
function reverse(matrix, i, j) {
const temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix.length - 1 - j];
matrix[i][matrix.length - 1 - j] = temp;
}
function transpose(matrix, i, j) {
const temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
const rotated = new Array(matrix.length).fill(null).map(v => new Array(matrix[0].length).fill(0));
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
rotated[j][matrix.length - 1 - i] = matrix[i][j];
}
}
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
matrix[i][j] = rotated[i][j];
}
}
};