Leetcode-Rotate Image

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度,规律 a[i][j]-->a[j][n-i] 

思路1.按规律逐行拷贝,需要开辟一个新的二维数组,空间复杂度略高

      2.按规律逐个元素和目标位置替换,发现每替换4次,坐标就会回到开始的地方

          以4*4的矩阵为例 a[0][0] --> a[0][3] --> a[3][3] -->a[3][0] --->a[0][0]

          元素4个一组分组,每遍历一行(n-1),最外圈的的元素构成的正方形就已经达成目标了

          缩小正方形逐行替换即可

 1 public class Solution {
 2         public void rotate(int[][] matrix) {
 3             if(matrix == null ||matrix.length <= 1){
 4                 return;
 5             }
 6             int n = matrix.length;
 7             int rectangleLen = n;
 8             int row = 0;
 9             while(rectangleLen >=2){
10                 for(int i =row;i<= n-2 - row ;i++){
11                     rotateRectangle(matrix,n,row,i);    
12                 }
13                 rectangleLen-= 2;
14                 row ++;
15             }
16         }
17         
18         public void rotateRectangle(int[][] matrix,int n,int x_pos,int y_pos){
19             int temp = matrix[x_pos][y_pos];
20             int target  = 0;
21             int temp_pos = 0;
22             for(int i=0;i<4;i++){
23                 target = temp;
24                 //target position
25                 temp_pos = x_pos;
26                 x_pos = y_pos;
27                 y_pos = n - 1 - temp_pos;
28                 temp  = matrix[x_pos][y_pos];
29                 //replace
30                 matrix[x_pos][y_pos] = target; 
31             }
32         }
33 }

 

posted @ 2014-09-02 15:30  dijkstra-c  阅读(119)  评论(0编辑  收藏  举报