Rotate Image
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]Last updated
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]Last updated
public void rotate(int[][] matrix) {
int len = matrix.length;
// the times needed to rotate is the half of the len
for (int i = 0; i < (len + 1) / 2; i++) {
for (int j = 0; j < len / 2; j++) {
// record the number at the bottom-left corner
int temp = matrix[len - 1 - j][i]; // note that the i and j in matrix[][] rotates
// replace bottom-left into the bottom-right corner
matrix[len - 1 - j][i] = matrix[len - 1 - i][len - j - 1];
// replace bottem-right into top-left
matrix[len - 1 - i][len - j - 1] = matrix[j][len - 1 - i];
// replace top-left with top-right corner
matrix[j][len - 1 - i] = matrix[i][j];
matrix[i][j] = temp;
}
}
} public void rotate(int[][] matrix) {
transpose(matrix);
reflect(matrix);
}
public void transpose(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // note here is j = i + 1 because at the element at j = i does not need to be moved
int tmp = matrix[j][i];
matrix[j][i] = matrix[i][j];
matrix[i][j] = tmp;
}
}
}
public void reflect(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) { // n / 2 because we're swapping the left and right
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][n - j - 1];
matrix[i][n - j - 1] = tmp;
}
}
}