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*n的矩阵,顺时针转90度,先关于主对角线交换,再将列对称交换
比如
1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 |
1 | 5 | 9 | 13 |
2 | 6 | 10 | 14 |
3 | 7 | 11 | 15 |
4 | 8 | 12 | 16 |
13 | 9 | 5 | 1 |
14 | 10 | 6 | 2 |
15 | 11 | 7 | 3 |
16 | 12 | 8 | 4 |
public class Solution {
public void rotate(int[][] matrix) {
int n=matrix.length;
int temp;
for(int i=0;i<n;i++) {
for(int j=0;j<i;j++) {
temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}
}
int start;
int end;
for(int i=0;i<n;i++) {
start=0;
end=n-1;
while(start<end) {
temp=matrix[i][start];
matrix[i][start]=matrix[i][end];
matrix[i][end]=temp;
start++;
end--;
}
}
}
}