题目
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?
思路
题目关键在于找到旋转时的对应关系即可,先复制一遍矩阵,然后对于点[i][j],其旋转后的位置为点[j][length-1-i],问题解决
代码
public class Solution {
public void rotate(int[][] matrix) {
int length = matrix.length;
int[][] mat=new int[length][length];
for(int i=0;i<length;++i){
for(int j=0;j<length;++j){
mat[i][j]=matrix[i][j];
}
}
for(int i = 0 ; i < length ; ++ i){
for(int j = 0 ; j < length ; ++ j){
//matrix[j][length-i-1] = mat[i][j];
matrix[i][j] = mat[length - j - 1][i];
}
}
}
}