우사미 코딩

[Leetcode] 48. Rotate Image - Matrix 본문

Leetcode

[Leetcode] 48. Rotate Image - Matrix

맑은 눈의 우사미 2023. 5. 19. 16:09
반응형

1. 문제링크

 

Rotate Image - LeetCode

Can you solve this real interview question? Rotate Image - 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 [https://en.wikipedia.org/wiki/In-place_algorithm], which m

leetcode.com

 

 

2. 매트릭스 변환 2회

1) mat[i][j] <-> mat[j][i] 

1 2 3      1 4 7

4 5 6 ->  2 5 8  

7 8 9      3 6 9

 

2) 각 row를 revers

1 4 7       7 4 1 

2 5 8  ->  8 5 2

3 6 9       9 6 3

 

 

3. solution

class Solution {
public:
    void rotate(vector<vector<int>>& mat) {
        int n = mat.size();

        for(int i = 0; i < n; i++){
            for(int j = 0; j <= i; j++){
                swap(mat[i][j], mat[j][i]);
            }
        }

        for(int i = 0; i < n; i++){
            reverse(mat[i].begin(), mat[i].end());
        }
    }
};

 

 

반응형
Comments