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?
思路:順時針旋轉90度,即將數組繞其中心順時針旋轉90度。問題關鍵在找到數組元素旋轉後的座標位置。可以通過座標變換將座標原點變換到數組中心處(數組本身的座標原點可以看作在0行0列處),這樣數組繞原點旋轉90度即可。空間複雜度爲O(1)。
代碼:
public void rotate(int[][] matrix) {
int n = matrix.length ;
if(n <= 1) return ;
float center = (float)(n-1)/2;
int x , y ;
int r , c ;
int buffer , temp;
for(int i = 0 ;i <= center ;i ++){
for(int j = 0 ;j < center ;j ++){
r = j ;
c = i ;
buffer = matrix[c][r] ;
for(int k = 0 ;k < 4 ;k ++){
// x = r - center ;
// y = c - center ;
// x = -y ;
// y = x ;
// x = x + center ;
// y = y + center ;
x = (int)(2*center) - c ;
y = r ;
temp = matrix[y][x] ;
matrix[y][x] = buffer ;
buffer = temp ;
r = x ;
c = y ;
}
}
}