[LeetCode] Rotate Image (JS)

nRecode·2020년 9월 14일
0

Algorithm

목록 보기
9/48

문제

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;
    
};
profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글