You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example2
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
처음에 이 문제를 접근할 때는 입출력의 입력과 출력의 패턴으로 파악을 해서 matrix의 마지막 인덱스부터 재분배하는 방법으로 진행을 하였으나, 배열을 따로 생성할 수 없기 때문에 변경을 할 때 계속해서 바뀌는 현상이 일어났다. 따라서 reverse 메소드를 이용하여 행과 열을 바꾸는 방법을 사용하였다.
var rotate = function(matrix) {
matrix = matrix.reverse();
for(let i = 0; i < matrix.length; i++){
for(let j = i; j < matrix.length; j++){
let temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
console.log(matrix)
}
return matrix;
};