N Log

2차원 배열 좌우 반전

문제

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

input:
[
    [  1,  2,  3,  4,  5 ],
    [ 11, 12, 13, 14, 15 ],
    [ 21, 22, 23, 24, 25 ]
]

output:
[
    [  5,  4,  3,  2,  1 ],
    [ 15, 14, 13, 12, 11 ],
    [ 25, 24, 23, 22, 21 ]
]

풀이

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

                int currentValue = matrix[row][col];
                matrix[row][col] = matrix[row][oppositeCol];
                matrix[row][oppositeCol] = 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 },
            { 11, 12, 13, 14, 15 },
            { 21, 22, 23, 24, 25 }
        };

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

        mirrorHorizontally(matrix);

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

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

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