(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?

使用先对角线翻转,后水平翻转

1      2              对角线翻转      4           2          水平翻转         3          1 

3      4             =========>    3           1       ==========>   4          2

 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int>>& matrix) {
 4         int n = matrix.size();
 5         int temp;
 6         for(int i = 0;i < n;++i)
 7         {
 8             for(int j = 0;j < n-i;++j)
 9             {
10                 temp = matrix[i][j];
11                 matrix[i][j] = matrix[n-j-1][n-i-1];
12                 matrix[n-j-1][n-i-1] = temp;
13             }
14         }
15         
16         for(int i = 0; i < n/2; ++i)//沿着水平线翻转
17         {
18             for(int j = 0;j < n;++j)
19             {
20                 temp = matrix[i][j];
21                 matrix[i][j] = matrix[n-i-1][j];
22                 matrix[n-i-1][j] = temp;
23             }
24         }
25     }
26 };

 

 

 

posted @ 2015-08-21 10:15  sunalive  Views(192)  Comments(0)    收藏  举报