public class Solution {
public void rotate(int[][] matrix) {
// Antidiagonal
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix.length - i; j++) {
swap(matrix, i, j, matrix.length - 1 - j, matrix.length - 1 - i);
}
}
// Up and down
for(int i = 0; i < matrix.length / 2; i++) {
for(int j = 0; j < matrix.length; j++) {
swap(matrix, i, j, matrix.length - 1 - i, j);
}
}
}
// Swaps matrix[i][j] and matrix[k][l]
private void swap(int[][] matrix, int i, int j, int k, int l) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[k][l];
matrix[k][l] = tmp;
}
}
Time: O(n^2)
Space: O(n)