码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Rotate Image

时间:2015-01-09 20:53:57      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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?

 
 
假设旋转的时候,左上角元素为(l,l),右下角元素为(r,r)
则旋转的时候
(l,l+1)=(r-1,l) 最上面一排 
(r-1,l)=(r,r-1)左边一排
(r,r-1)=(l+1,r)下面一排
(l+1,r)=(l,l+1)右边一排
 
可以找到规律
(i,j)--->(r+l-j,i)
 
 
 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int> > &matrix) {
 4        
 5         int n=matrix.size();
 6         int leftUp=0;
 7         int rightBottom=n-1;
 8         while(rightBottom>leftUp)
 9         {
10             int n0=rightBottom+leftUp;
11             for(int i=leftUp;i<rightBottom;i++)
12             {
13                 int tmp=matrix[leftUp][i];
14                 matrix[leftUp][i]=matrix[n0-i][leftUp];
15                 matrix[n0-i][leftUp]=matrix[n0-leftUp][n0-i];
16                 matrix[n0-leftUp][n0-i]=matrix[i][n0-leftUp];
17                 matrix[i][n0-leftUp]=tmp;
18  
19             }
20            
21             leftUp++;rightBottom--;
22         }
23     }
24 };

 

 
 

【leetcode】Rotate Image

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4214111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!