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?
思路:使用最基本的方法,递归,但是有空间复杂度
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void helper(vector<vector<int> >& vec,int n)
{
if(n == vec.size() || n+1 == vec.size())
return ;
int i = n/2,j = (vec.size()-1)-n/2; //i表示行 j表示列
vector<int> tmp(vec[i].begin()+i,vec[i].begin()+j+1);
int k,m;
for(k=i,m=j;k<=j;k++,m--)
vec[i][m]= vec[k][i];
for(k=i;k<=j;k++)
vec[k][i] = vec[j][k];
for(k=i,m=j;k<=j;k++,m--)
vec[j][k] = vec[m][j];
for(k=i,m=0;k<=j;k++,m++)
vec[k][j] = tmp[m];
helper(vec,n+2);
}
void RotateImage(vector<vector<int> >& vec)
{
if(vec.size()<=1)
return ;
helper(vec,0);
}
int main()
{
vector<int> vec(6,0);
vector<vector<int> > image;
int i,j;
for(i=0;i<vec.size();i++)
{
for(j=0;j<vec.size();j++)
vec[j] = i+j+1;
image.push_back(vec);
}
for(i=0;i<vec.size();i++)
{
for(j=0;j<vec.size();j++)
cout<<image[i][j]<<" ";
cout<<endl;
}
RotateImage(image);
cout<<"========="<<endl;
for(i=0;i<vec.size();i++)
{
for(j=0;j<vec.size();j++)
cout<<image[i][j]<<" ";
cout<<endl;
}
return 0;
}原文地址:http://blog.csdn.net/yusiguyuan/article/details/44924409