Problem Description
Given an n × n two-dimensional matrix matrix represents an image. Please rotate the image 90 degrees clockwise.
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:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]
Example 2:
输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Example 3:
输入:matrix = [[1]]
输出:[[1]]
Example 4:
输入:matrix = [[1,2],[3,4]]
输出:[[3,1],[4,2]]
prompt:
matrix.length == n
matrix[i].length == n
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
Problem-solving ideas (use flip instead of rotation):
We can also take a different approach and use flip operations instead of rotating operations. Example 1 Example We
we first flip The main diagonal, from
obtained
which then obtained by reversing the left and right horizontal axis
Implementation code:
class Solution {
public void rotate(int[][] matrix) {
//先转置,后镜像对称
//求行和列的长度
int row=matrix.length;
int col=matrix[0].length;
//求转置
for(int i=0;i<row-1;i++){
for(int j=i+1;j<col;j++){
int temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}
}
//水平镜像对称反转
for(int j=0;j<col/2;j++){
for(int i=0;i<row;i++){
int temp=matrix[i][j];
matrix[i][j]=matrix[i][col-1-j];
matrix[i][col-1-j]=temp;
}
}
}
}