記錄

48. Rotate Image 본문

FRONTEND STUDY/LeetCode

48. Rotate Image

prts 2022. 11. 19. 22:51

문제 링크: https://leetcode.com/problems/rotate-image/description/
난이도: Medium

문제 설명

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.

 

주어진  n x n 2D 매트릭스 이미지를 90도(시계 방향) 회전합니다.
이미지를 제자리에서 회전해야 합니다. 즉, 입력 2D 매트릭스를 직접 수정해야 합니다.

다른 2D 매트릭스를 할당하고 회전하지 마십시오.

 

Example 1:

 

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

 

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]]

제한사항

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

 

관련 주제: Array, Math, Matrix

 

문제 풀이

 

2차원 배열을 회전시키는 문제이다.

배열 내 요소를 [row, col] 좌표 형태로 바꿔서 회전한 이후의 값을 비교해서 규칙을 찾아본다.

*참고: https://tasddc.tistory.com/108

var rotate = function(matrix) {
    //시계방향으로 90도 회전하는 2d matrix 
    //[0,0][0,1][0,2] => [0,2][1,2][2,2] 행=기존 열 값 => [i][j]=[j][i]
    //[1,0][1,1][1,2] => [0,1][1,1][2,1] 열=최대 index(length-1)-기존 행 값 (0) => matrix.length - 1 - j
    //[2,0][2,1][2,2] => [0,0][1,0][2,0]

    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
        }
    }
    let mid = Math.floor(matrix.length / 2)
    
    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < mid; j++) {
            let temp = matrix[i][j]
            matrix[i][j] = matrix[i][matrix.length - 1 - j]
            matrix[i][matrix.length - 1 - j] = temp
        }
    }
};

 

'FRONTEND STUDY > LeetCode' 카테고리의 다른 글

3. Longest Substring Without Repeating Characters  (0) 2022.11.05
28. Find the Index of the First Occurrence in a String  (0) 2022.10.28
20. Valid Parentheses  (0) 2022.10.25
120. Triangle  (0) 2022.10.24
[JS] 386. Lexicographical Numbers  (0) 2022.10.20
Comments