Rotate Image
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place?
Solution
public class Solution {
public void rotate(int[][] matrix) {
rotate(matrix, matrix.length, 0, matrix.length - 2);
}
public void rotate(int[][] matrix, int n, int level, int maxJ) {
if (maxJ < 0) {
return;
} else {
int i = level;
for (int j = 0; j <= maxJ; j++) {
int tmp = matrix[i][i + j];
matrix[i][i + j] = matrix[n - i - j - 1][i];
matrix[n - i - j - 1][i] = matrix[n - i - 1][n - i - j - 1];
matrix[n - i - 1][n - i - j - 1] = matrix[i + j][n - i - 1];
matrix[i + j][n - i - 1] = tmp;
}
rotate(matrix, n, level + 1, maxJ - 2);
}
}
}