|
| 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 | +classSolution { |
| 8 | +publicvoidrotate(int[][]matrix) { |
| 9 | +intN =matrix.length; |
| 10 | + |
| 11 | +transpose(matrix,N); |
| 12 | +reverse(matrix,N); |
| 13 | + } |
| 14 | + |
| 15 | +voidtranspose(int[][]matrix,intn) { |
| 16 | +for (inti =0;i <n;i++) { |
| 17 | +for (intj =i +1;j <n;j++) { |
| 18 | +inttemp =matrix[j][i]; |
| 19 | +matrix[j][i] =matrix[i][j]; |
| 20 | +matrix[i][j] =temp; |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | +voidreverse(int[][]matrix,intn) { |
| 26 | +for (inti =0;i <n;i++) { |
| 27 | +for (intj =0;j <n /2;j++) { |
| 28 | +inttemp =matrix[i][j]; |
| 29 | +matrix[i][j] =matrix[i][n -1 -j]; |
| 30 | +matrix[i][n -1 -j] =temp; |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | +} |