您的位置:首页 > 其它

48. Rotate Image ---leetcode算法笔记

2016-06-30 09:16 405 查看
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 ;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Rotate Image leetcod