48. Rotate Image(旋转矩阵) (先水平,再对角线)

 

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

 

Example 2:

Given input matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix in-place such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

先上下翻转,然后在对称翻转。
/*
 * clockwise rotate
 * first reverse up to down, then swap the symmetry 
 * 1 2 3     7 8 9     7 4 1
 * 4 5 6  => 4 5 6  => 8 5 2
 * 7 8 9     1 2 3     9 6 3
*/


class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        
        // 先水平,再斜对角线,也可以先上下,再正对角线
        int n = matrix.size();
        //水平镜像
        for(int i =0; i < n;i++) {
            reverse(matrix[i].begin(),matrix[i].end());
        }
        // 斜对角线翻转
        for (int i = 0; i < n-1; ++i) {
            for (int j = 0; j < n-i; ++j) {
                swap(matrix[i][j], matrix[n-j-1][n-i-1]);
            }
        }
        //
    }
};

 



 1 class Solution {
 2     
 3      public void rotate(int[][] matrix) {
 4             int rows = matrix.length - 1;
 5             int cols = matrix[0].length - 1;
 6             for(int i = 0;i <=rows/2;i++)
 7                 for(int j = 0;j <= cols;j++ )
 8                 swap2(matrix,i,j,cols-i,j);
 9             
10             for(int i = 0;i<=rows;i++)
11                 for(int j =i+1;j<=cols;j++)
12                     swap2(matrix, i, j,j,i);
13         }
14     
15         private void swap2(int[][] a,int i1,int j1,int i2,int j2) {
16             int temp = a[i1][j1];
17             a[i1][j1] = a[i2][j2];
18             a[i2][j2] = temp;
19             
20         }
21         
22 
23     
24 }

 

posted @ 2018-03-26 16:46  乐乐章  阅读(201)  评论(0编辑  收藏  举报