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?
思路:先将矩阵转置,然后第一列和最后一列交换,第二列和倒数第二列交换,第三列和倒数第三列交换….直到第n/2列和倒数第n/2列交换完成即为最终的结果。
public class Solution {
public void rotate(int[][] matrix) {
int n=matrix.length;
if(n<=0) return;
int m=matrix[0].length;
if(m!=n) return;
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{ int temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}
}
for(int j=0;j<=(n-1)/2;j++)
{
for(int i=0;i<n;i++)
{ int temp=matrix[i][j];
matrix[i][j]=matrix[i][n-1-j];
matrix[i][n-1-j]=temp;
}
}
return;
}
}