|
| 1 | +class Solution { |
| 2 | + |
| 3 | + // 공간복잡도 개선 및 별도의 방문 배열 처리 등 하지 않기 위해 |
| 4 | + // 2nd solution |
| 5 | + public void rotate(int[][] matrix) { |
| 6 | + |
| 7 | + int n = matrix.length; |
| 8 | + |
| 9 | + // 행, 열 자리 바꾸기 |
| 10 | + for (int i = 0; i < n; i++) { |
| 11 | + for (int j = i + 1; j < n; j++) { |
| 12 | + int temp = matrix[i][j]; |
| 13 | + matrix[i][j] = matrix[j][i]; |
| 14 | + matrix[j][i] = temp; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + // 열 자리 swap 하기 |
| 19 | + // ex) 3 X 3 => 0 <-> 2 열 스왑 |
| 20 | + // ex) 4 x 4 => 0 <-> 3, 1 <-> 2 스왑 |
| 21 | + for (int i = 0; i < n; i++) { |
| 22 | + for (int j = 0; j < n / 2; j++) { |
| 23 | + int temp = matrix[i][j]; |
| 24 | + matrix[i][j] = matrix[i][n - 1 - j]; |
| 25 | + matrix[i][n - 1 - j] = temp; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + // public void rotate(int[][] matrix) { |
| 32 | + |
| 33 | + // [0, 0], [0, 1], [0, 2] [2, 0], [1, 0], [0, 0] |
| 34 | + // [1, 0], [1, 1], [1, 2] [2, 1], [1, 1], [0, 1] |
| 35 | + // [2, 0], [2, 1], [2, 2] [2, 2], [2, 1], [0, 2] |
| 36 | + |
| 37 | + |
| 38 | + // [0, 0], [0, 1], [0, 2], [0, 3] [3, 0], [2, 0], [1, 0], [0, 0] |
| 39 | + // [1, 0], [1, 1], [1, 2], [1, 3] [3, 1], [2, 1], [1, 1], [0, 1] |
| 40 | + // [2, 0], [2, 1], [2, 2], [2, 3] [3, 2], [2, 2], [1, 2], [0, 2] |
| 41 | + // [3, 0], [3, 1], [3, 2], [3, 3] [3, 3], [2, 3], [1, 3], [0, 3] |
| 42 | + |
| 43 | + // 90D => |
| 44 | + // n = matrix.length이고 m = matrix[0].length일 때 |
| 45 | + // 1 => 3 matrix[0][0] => matrix[0][2] |
| 46 | + // 2 => 6 matrix[0][1] => matrix[1][2] |
| 47 | + // 3 => 9 matrix[0][2] => matrix[2][2] |
| 48 | + // matrix[i][j] => matrix[j][n - 1 - i] |
| 49 | + |
| 50 | + // int n = matrix.length; |
| 51 | + // int m = matrix[0].length; |
| 52 | + |
| 53 | + // boolean[][] visited = new boolean[n][m]; |
| 54 | + |
| 55 | + // for (int i = 0; i < n; i++) { |
| 56 | + // for (int j = 0; j < m; j++) { |
| 57 | + // if (visited[i][j]) { |
| 58 | + // continue; |
| 59 | + // } |
| 60 | + // int temp = matrix[i][j]; |
| 61 | + // matrix[i][j] = matrix[j][n - 1 - i]; |
| 62 | + // matrix[j][n - 1 - i] = temp; |
| 63 | + |
| 64 | + // visited[i][j] = true; |
| 65 | + // visited[j][n - 1 - i] = true; |
| 66 | + // } |
| 67 | + // } |
| 68 | + // } |
| 69 | +} |
| 70 | + |
0 commit comments