본문 바로가기
LeetCode

[LeetCode] 48. Rotate Image

by JungSeung 2023. 11. 10.
728x90

https://leetcode.com/

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.

 

Example 1:

출처 : https://leetcode.com/problems/rotate-image/description/

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

 

Example 2:

출처 : https://leetcode.com/problems/rotate-image/description/

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

 

Constraints:

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

 

Code :

var rotate = function(matrix) {
    // 행렬의 크기를 구합니다.
    const n = matrix.length;
    // 행렬을 회전시키는 과정을 수행합니다.
    for (let i = 0; i < n; i++) {
        // 대각선을 기준으로 대칭인 요소들을 교환합니다.
        for (let j = 0; j < i; j++) {
            [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
        }
    }
    // 각 행을 뒤집어 주어 행렬을 시계 방향으로 90도 회전시킵니다.
    for (let i = 0; i < n; i++) {
        matrix[i].reverse();
    }
};

 

Solutions Code : 

var rotate = function(M) {
	// 배열의 길이와 깊이 변수 설정
    let n = M.length, depth = ~~(n / 2);
    // 반복문을 통해 회전 수행
    for (let i = 0; i < depth; i++) {
    	// 현재 깊이에 따른 길이와 반대편 인덱스 설정
        let len = n - 2 * i - 1, opp = n - 1 - i;
        // 회전 작업을 수행하는 반복문
        for (let j = 0; j < len; j++) {
            let temp = M[i][i+j]; // 임시 변수를 사용하여 회전 작업 수행
            M[i][i+j] = M[opp-j][i]; // 회전 작업 수행
            M[opp-j][i] = M[opp][opp-j]; // 회전 작업 수행
            M[opp][opp-j] = M[i+j][opp]; // 회전 작업 수행
            M[i+j][opp] = temp; // 회전 작업 수행
        }
    }
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 50. Pow(x, n)  (0) 2023.11.10
[LeetCode] 49. Group Anagrams  (0) 2023.11.10
[LeetCode] 47. Permutations II  (0) 2023.11.10
[LeetCode] 46. Permutations  (0) 2023.11.09
[LeetCode] 45. Jump Game II  (2) 2023.11.09