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.
주어진 2차원 배열을 시계 방향으로 90도 돌리는 문제에요. 그리고 In-place
, 즉 다른 배열을 추가로 만들지 않고 오롯이 주어진 배열을 통해서 돌려야하는 문제에요.
방법만 안다면 쉽게 풀 수 있어요.
- 배열을
Transpose
처리- 배열을
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;
}
}
}
}