首页 > 代码库 > 【leetcode】Rotate Image

【leetcode】Rotate Image

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