개발조각

[리트코드] 48. Rotate Image 본문

알고리즘🅰/리트코드

[리트코드] 48. Rotate Image

개발조각 2022. 10. 24. 19:44
728x90
반응형

문제

https://leetcode.com/problems/rotate-image/

 

Rotate Image - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

소스코드

var rotate = function(matrix) {        
    let length = matrix.length;
    let arr = [];
    let direction1 = 1;
    let [x, y] = [-1, 0];
    
    while(1){
        for(let i=0; i<length; i++){
            x += direction1;
            arr.push(matrix[y][x]);
        }
        length--;
        
        if(length === 0) break;
        
        for(let j=0; j<length; j++){
            y += direction1;
            arr.push(matrix[y][x]);
        }
        direction1 *= -1; // 방향
    }
    
    let length2 = matrix.length;
    let direction2 = 1;
    let count = matrix.length-2;
    let [x2, y2] = [length2-1, -1];
    
    while(1){
        if(length2 === 0) break;
        
        for(let i=0; i<length2; i++){
            y2 += direction2;
            matrix[y2][x2] = arr.shift();
        }
        length2--;
        direction2 *= -1; // 방향  
        
        for(let j=0; j<length2; j++){
            x2 += direction2;
            matrix[y2][x2] = arr.shift();
        }
    }
    return matrix;
};

이 코드를 보시면 크게 두 분류로 나누어져 있습니다.

 

1번

let length = matrix.length;
let arr = [];
let direction1 = 1;
let [x, y] = [-1, 0];

while(1){
    for(let i=0; i<length; i++){
        x += direction1;
        arr.push(matrix[y][x]);
    }
    length--;

    if(length === 0) break;

    for(let j=0; j<length; j++){
        y += direction1;
        arr.push(matrix[y][x]);
    }
    direction1 *= -1; // 방향
}

 

2번

let length2 = matrix.length;
let direction2 = 1;
let count = matrix.length-2;
let [x2, y2] = [length2-1, -1];

while(1){
    if(length2 === 0) break;

    for(let i=0; i<length2; i++){
        y2 += direction2;
        matrix[y2][x2] = arr.shift();
    }
    length2--;
    direction2 *= -1; // 방향  

    for(let j=0; j<length2; j++){
        x2 += direction2;
        matrix[y2][x2] = arr.shift();
    }
}
return matrix;

이러한 예제가 있으면

1번 코드는 1 → 2 → 3 → 6 → 9 → 8 → 7 → 4 →5 이런 순으로 진행이 되는 코드이고

2번 코드는 3 → 6 → 9 → 8 → 7 → 4 → 1 → 2 →5 이런 순으로 진행되는 코드입니다.

 

1번 코드는 [0][0]부터 시작하는 달팽이 사각형이고

2번 코드는 [0][2]부터 시작하는 기존 달팽이 사각형에서 90도 회전한 방식으로 된 달팽이 사각형입니다.

 

그래서 1번에서 기존 달팽이 사각형의 순서를 저장하고

2번에 1번 코드에서 담아준 배열을 통해 맞는 값을 넣어주는 방식으로 해결해 주었습니다.

 

Example1로 1번 코드만 실행할 경우

console.log(arr);

[
  1, 2, 3, 6, 9,
  8, 7, 4, 5
]

이러한 값이 나오고

이 순서대로 원하는 방향으로 2번코드에서 metrix값을 변경해주었습니다.

이해가 안되시면 직접 적어보면서 풀어보시는 걸 추천드립니다.😀


728x90
반응형

'알고리즘🅰 > 리트코드' 카테고리의 다른 글

[리트코드] 49. Group Anagrams  (0) 2022.10.26
[리트코드] 50. Pow(x, n)  (0) 2022.10.25
[리트코드] 46. Permutations  (0) 2022.10.09
[리트코드] 43. Multiply Strings  (0) 2022.10.08
[리트코드] 39. Combination Sum  (0) 2022.10.05
Comments