N Log

2차원 배열 상하 반전

문제

배열을 입력받아 새 배열을 만들지 않고 원본 배열을 상하로 반전하는 함수를 작성하시오.

input:
[
    [  1,  2,  3 ],
    [  4,  5,  6 ],
    [  7,  8,  9 ],
    [ 10, 11, 12 ],
    [ 13, 14, 15 ]
]

output:
[
    [ 13, 14, 15 ],
    [ 10, 11, 12 ],
    [  7,  8,  9 ],
    [  4,  5,  6 ],
    [  1,  2,  3 ]
]

풀이

class Main {
    public static void mirrorVertically(int[][] matrix) {
        for (int row = 0; row < matrix.length / 2; row++) {
            int oppositeRow = matrix.length - 1 - row;

            for (int col = 0; col < matrix[row].length; col++) {
                int currentValue = matrix[row][col];

                matrix[row][col] = matrix[oppositeRow][col];
                matrix[oppositeRow][col] = currentValue;
            }
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int row = 0; row < matrix.length; row++) {
            for (int col = 0; col < matrix[row].length; col++) {
                System.out.printf("%3d", matrix[row][col]);
            }

            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {  1,  2,  3 },
            {  4,  5,  6 },
            {  7,  8,  9 },
            { 10, 11, 12 },
            { 13, 14, 15 }
        };

        System.out.println("input:");
        printMatrix(matrix);

        mirrorVertically(matrix);

        System.out.println();
        System.out.println("output:");
        printMatrix(matrix);
    }
}

상하 반전은 새 배열을 만들어 결과를 채우는 out-of-place 방식인지, 원본 배열을 직접 수정하는 in-place 방식인지에 따라 풀이가 달라진다.
out-of-place 방식이라면 원본 배열의 모든 칸을 방문하면서 새 배열의 마지막 행부터 값을 채우면 된다.
하지만 이 문제는 in-place 방식이므로, 위쪽 행의 값과 아래쪽 행의 값을 서로 교환해야 한다.
위쪽 끝과 아래쪽 끝에서 시작해 안쪽으로 이동하면서 같은 열에 있는 두 값을 바꾸면 된다.

교환을 위해 접근하는 행 인덱스를 생각해보자.
5x3 배열을 기준으로 보면 0번 행은 4번 행과 바뀌고, 1번 행은 3번 행과 바뀐다.
가운데 2번 행은 자기 자신과 짝이 되므로 교환할 필요가 없다.