題目
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];
}
}
}
}