기기

배열 회전 본문

CS/Algorithm

배열 회전

notEmpty 2020. 5. 3. 19:51

백준에서 Maaaaaaaaaze 문제를 풀고 다른 사람 풀이를 봤었다. 

 

그런데, 배열 회전에서 차이가 있었다

 

 

처음 배열 회전 시킬 때, 그냥 한 칸씩 이동하는 과정을 여러 번 반복했었다. 

 

하지만, 회전의 특징? 을 고려하면 더 빠르고 깔끔하게 코드를 짤 수 있었다. 

 

 

말로 설명하는 것보단 그림을 보는 것이 바로 이해하기 좋기 때문에 그림으로 대체.. 

 

 

 

이 그림대로 모든 좌표 ( y, x) 를 ( x, height - y - 1 )로 바꾸면 간단하게 90 회전한 배열을 구할 수 있다. 

 

사실 이걸 몰라도 어떻게든 회전할 수 있지만, 이 방법을 알아두는게 좋을 것 같아 따로 정리했다. 

 

 

 

 

 

구현 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Main {
    public static void main(String[] args) throws IOException {
        
        // 초기 배열 값 
        int[][] matrix = {
            { 12 },
            { 34},
            { 56},
            { 78}
        };
        
        // 4번 회전
        for(int iter = 0 ; iter < 4 ; iter++) {
            matrix = rotate90(matrix);
            print(matrix);
        }
    }
    
    static int[][] rotate90(int[][] matrix) {
        int height = matrix.length;
        int width = matrix[0].length;
        
        // 높이, 너비를 바꿔 새로운 rotated Matrix 배열을 만든다. 
        int[][] rotatedMatrix = new int[width][height];
        
        // 식에 따라 회전 
        for(int y = 0 ; y < height ; y++) {
            for(int x = 0 ; x < width ; x++) {
                rotatedMatrix[x][height - y - 1= matrix[y][x];
            }
        }
        
        return rotatedMatrix;
    }
    
 
    static void print(int[][] matrix) {
        
        for(int y = 0 ; y < matrix.length ; y++) {
            for(int x = 0 ; x < matrix[0].length ; x++) {
                System.out.print(matrix[y][x]+" ");
            }
            System.out.println();
        }
        System.out.println();
    }
}
cs

 

 

결과 

배열 

1 2 

3 4

5 6

7 8

을 회전할 결과 

 

'CS > Algorithm' 카테고리의 다른 글

이진 탐색 ( + 하한 lower_bound, 상한upper_bound )  (0) 2023.12.05
투 포인터  (0) 2023.05.06
Binary Search Tree  (0) 2020.03.26
tree 자료구조  (0) 2020.03.25
구현) 정렬  (0) 2020.03.21