|
1 | | -// Do note that this is for a sqaure matrix (NxN) |
2 | | -// The process is to first transpose the matrix and then reverse it |
3 | | -// Taking the first example: [[1,2,3],[4,5,6],[7,8,9]] |
4 | | -// After Transpose: [[1,4,7],[2,5,8],[3,6,9]] |
5 | | -// After Reversal: [[7,4,1],[8,5,2],[9,6,3]] |
6 | | - |
7 | 1 | class Solution { |
8 | | - |
9 | 2 | public void rotate(int[][] matrix) { |
10 | | - int N = matrix.length; |
| 3 | + int l = 0; |
| 4 | + int r = matrix.length - 1; |
| 5 | + |
| 6 | + while ( l < r ) |
| 7 | + { |
| 8 | + for(int i = 0; i < r - l; i++) |
| 9 | + { |
| 10 | + int top = l; |
| 11 | + int bottom = r; |
| 12 | + //save the topleft |
| 13 | + int topLeft = matrix[top][l + i]; |
11 | 14 |
|
12 | | - transpose(matrix, N); |
13 | | - reverse(matrix, N); |
14 | | - } |
| 15 | + //move bottom left into top left |
| 16 | + matrix[top][l + i] = matrix[bottom - i][l]; |
15 | 17 |
|
16 | | - void transpose(int[][] matrix, int n) { |
17 | | - for (int i = 0; i < n; i++) { |
18 | | - for (int j = i + 1; j < n; j++) { |
19 | | - int temp = matrix[j][i]; |
20 | | - matrix[j][i] = matrix[i][j]; |
21 | | - matrix[i][j] = temp; |
22 | | - } |
23 | | - } |
24 | | - } |
| 18 | + // move bottom right into bottom left |
| 19 | + matrix[bottom - i][l] = matrix[bottom][r - i]; |
| 20 | + |
| 21 | + // move top right into bottom right |
| 22 | + matrix[bottom][r - i] = matrix[top + i][r]; |
25 | 23 |
|
26 | | - void reverse(int[][] matrix, int n) { |
27 | | - for (int i = 0; i < n; i++) { |
28 | | - for (int j = 0; j < n / 2; j++) { |
29 | | - int temp = matrix[i][j]; |
30 | | - matrix[i][j] = matrix[i][n - 1 - j]; |
31 | | - matrix[i][n - 1 - j] = temp; |
| 24 | + // move top left into top right |
| 25 | + matrix[top + i][r] = topLeft; |
| 26 | + |
32 | 27 | } |
| 28 | + |
| 29 | + r -= 1; |
| 30 | + l += 1; |
33 | 31 | } |
34 | 32 | } |
35 | 33 | } |
0 commit comments