가로와 세로가 같은 n x n 배열에서는 별도의 배열 선언 없이 배열의 값을 직접 회전시킬 수 있다.
아래는 변환 과정을 나타낸다.
1
2
3
4
5
6
7
8
9
=>
7
8
9
4
5
6
1
2
3
=>
7
4
1
8
5
2
9
6
3
public void rotate(int[][] matrix) { int n = matrix.length; // 위 아래를 뒤집는다. for(int row = 0 ; row < n / 2; row++) { for(int col = 0 ; col < n; col++) { int tp = matrix[row][col]; matrix[row][col] = matrix[n - row - 1][col]; matrix[n - row - 1][col] = tp; } } // 왼쪽 아래 => 오른쪽 아래 방향으로 그어진 대각선을 기준으로 뒤집는다. for(int row = 0 ; row < n; row++){ for(int col = row; col < n; col++){ int tp = matrix[row][col]; matrix[row][col] = matrix[col][row]; matrix[col][row] = tp; } }}
일반적인 케이스
회전을 원하는 2차원 배열의 경우 별도의 rotate 배열을 선언한 다음에 옮기는 작업을 진행하면 된다.
public void rotate(int[][] matrix) { int n = matrix.length; int m = matrix[0].length; int[][] rotate = new int[m][n]; for(int row = 0 ; row < m; row++) { for(int col = 0 ; col < n; col++) { rotate[row][col] = matrix[n - col - 1][row]; } }}
반시계방향 90도 회전
시계 방향과 마찬 가지로 별도의 rotate 배열을 선언한 다음에 변환하는 작업을 진행하면 된다.
public void rotate(int[][] matrix) { int n = matrix.length; int m = matrix[0].length; int[][] rotate = new int[m][n]; for(int row = 0 ; row < m; row++) { for(int col = 0 ; col < n; col++) { rotate[row][col] = matrix[col][n - row - 1]; } }}