[codeSignal] rotateImage

반응형
반응형

Note: Try to solve this task in-place (with O(1) additional memory), since this is what you'll be asked to do during an interview.

You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).

Example

For

a = [[1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]]

the output should be

rotateImage(a) = [[7, 4, 1],

                       [8, 5, 2],

                       [9, 6, 3]]

 

간단히 배열을 옮기는 비교적 간단한 문제다.

처음에 접근을 종이에 어떻게 배열이 회전하는지 그려보았다.

 

0,0 -> 0,2

0,1 -> 1,2

0,2 -> 2,2

===========

1,0 -> 0,1

1,1 -> 1,1

1,2 -> 2,1

==============

2,0 -> 0,0

2,1 -> 1,0

2,2 -> 2,0

 

전체적으로 살펴보면

1씩 감소되는 모습이고

낱개로 확인하면 

감소가 되지 않는 상태였다.

이것을 코드로 나타내보면

int[][] rotateImage(int[][] a) {
    int[][] b = new int[a.length][a.length];
    
    for(int i = 0; i<a.length;i++) {
        for(int j = a.length-1; j>-1;j--) {
            b[i][j] = a[a.length-j-1][i];
        }
    }
    
    return b;
}

비교적 간단하게 답이 호출되는걸 알 수있다.

0,2 <= 0,0 뭐 이런식이다.

 

int[][] rotateImage(int[][] a) {
    int n = a.length;
    for(int i = 0; i < n / 2; i++){
        for(int j = i; j < n-i-1; j++){
            int temp = a[i][j];
            a[i][j] = a[n-j-1][i];
            a[n-j-1][i] = a[n-1-i][n-1-j];
            a[n-1-i][n-1-j] = a[j][n-1-i];
            a[j][n-1-i] = temp;
        }
    }
    return a;
}
반응형

'알고리즘' 카테고리의 다른 글

[code-up] 성실한 개미  (0) 2020.08.12
[codeSignel] Minesweeper  (0) 2020.07.23
[codeSignal] avoidObstacles  (0) 2020.07.18
[codesignal] isIPv4 address  (0) 2020.07.16
[codesignal] commonCharacterCount  (0) 2020.07.13

댓글

Designed by JB FACTORY