Given an n × n two-dimensional matrix represents an image.
Rotate the image 90 degrees clockwise.
Description:
You have to rotate the image in place, which means you need to directly modify the input two-dimensional matrix. Please do not use another matrix to rotate the image.
Example 1:
Given matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
Rotate the input matrix in place so that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given matrix =
[
[5, 1, 9,11],
[2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
Rotate the input matrix in place so that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11 ]
]
Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/rotate-image
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
class Solution {
public void rotate(int[][] matrix) {
//还是太菜了,第一想法,还是要通过另一个矩阵才能写出来
//偷个懒,不找规律直接看题解,hhhhhhh
int n = matrix.length;
for (int i = 0; i < n / 2; ++i) {
//奇偶数行都符合n/2
for (int j = 0; j < (n + 1) / 2; ++j) {
//列的话 n为奇数要多加一列
int temp = matrix[i][j];
matrix[i][j] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
matrix[j][n - i - 1] = temp;
}
}
}
}