菱纱梦

导航

Rotate Image <leetcode>

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 class Solution {
 2 public:
 3     void rotate(vector<vector<int> > &matrix) {
 4         int n=matrix.size();
 5         if(n==1)  return;
 6         for(int i=0;i<n;i++)
 7         {
 8             for(int j=0;j<n/2;j++)
 9             {
10                 swap(matrix[i][j],matrix[i][n-j-1]);
11                 
12             }
13         }
14         for(int i=0;i<n;i++)
15         {
16             for(int j=0;j<n-i;j++)
17             {
18                 swap(matrix[i][j],matrix[n-j-1][n-i-1]);
19             }
20         }
21     }
22 };

 

posted on 2014-09-03 19:10  菱纱梦  阅读(135)  评论(0编辑  收藏  举报