【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)
 
 class Solution {
public:
void rotate(vector<vector<int> > &matrix) { int n=matrix.size();
int leftUp=;
int rightBottom=n-;
while(rightBottom>leftUp)
{
int n0=rightBottom+leftUp;
for(int i=leftUp;i<rightBottom;i++)
{
int tmp=matrix[leftUp][i];
matrix[leftUp][i]=matrix[n0-i][leftUp];
matrix[n0-i][leftUp]=matrix[n0-leftUp][n0-i];
matrix[n0-leftUp][n0-i]=matrix[i][n0-leftUp];
matrix[i][n0-leftUp]=tmp; } leftUp++;rightBottom--;
}
}
};
 
 
上一篇:算法竞赛之递归——输出1-n的所有排列


下一篇:为什么以sys无法远程登录数据库