[LeetCode][Java] Rotate Image

최지수·2022년 3월 9일
0

Algorithm

목록 보기
67/77
post-thumbnail

문제

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, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

제한사항

  • n == matrix.length == matrix[i].length
  • 1 \leq n \leq 20
    -1000 \leq matrix[i][j] \leq 1000

접근

주어진 2차원 배열을 시계 방향으로 90도 돌리는 문제에요. 그리고 In-place, 즉 다른 배열을 추가로 만들지 않고 오롯이 주어진 배열을 통해서 돌려야하는 문제에요.

방법만 안다면 쉽게 풀 수 있어요.

  1. 배열을 Transpose 처리
  2. 배열을 y축 기준으로 Rotate 처리

답안

class Solution {
    
    public void rotate(int[][] matrix) {
        transpose(matrix);
        reverseY(matrix);
    }

    private void transpose(int[][] matrix){
        for(int i = 0; i < matrix.length - 1; ++i){
            for(int j = i + 1 ; j < matrix.length; ++j){
                int tmp = matrix[j][i];
                matrix[j][i] = matrix[i][j];
                matrix[i][j] = tmp;
            }
        }
    }

    private void reverseY(int[][] matrix){
        for(int i = 0; i < matrix[0].length / 2; ++i){
            for(int j = 0; j < matrix.length; ++j){
                int tmp = matrix[j][i];
                matrix[j][i] = matrix[j][matrix[0].length - i - 1];
                matrix[j][matrix[0].length - i - 1] = tmp;
            }
        }
    }
}
profile
#행복 #도전 #지속성

0개의 댓글