//Given an image represented by an NxN matrix, where each pixel in the image is 4
//bytes, write a method to rotate the image by 90 degrees Can you do this in place?
//int 4 byte!!!
#include<iostream>
#include<string>
using namespace std;
#define N 10
struct matrix
{
int pixel[N][N];//declaration
};
//1 int 4 bytes
//2 layer,先编出基本的(最边上),然后用变量代替
//3 from corner
void rotateInPlace(matrix &m)
{
int top;
int first;
int last;
int offset;
for(int layer=0;layer<N/2;layer++)
{
first=layer;
last= N-1-first;
for(int i=first;i<last;i++)
{
offset=i-first;
//分四步
top=m.pixel[first+offset][first];
m.pixel[first+offset][first]=m.pixel[last][i];
m.pixel[last][i]=m.pixel[last-offset][last];
m.pixel[last-offset][last]=m.pixel[first][last-offset];
m.pixel[first][last-offset]=top;
}
}
}
void printMatrix(matrix m)
{ for(int j=0;j<N;j++)
{
for(int i=0;i<N;i++)
{
cout<<m.pixel[j][i]<<" ";
}
cout<<endl;
}
}
void main()
{
matrix *m=new matrix;
for(int j=0;j<N;j++)
{
for(int i=0;i<N;i++)
{
m->pixel[j][i]=j*10+i;
}
}
printMatrix(*m);
rotateInPlace(*m);
cout<<"after rotating once:"<<endl;
printMatrix(*m);
rotateInPlace(*m);
cout<<"after rotating twice:"<<endl;
printMatrix(*m);
}
//学习到的 1 in place 是不开辟新的空间
// 2 int就是4个 byte
// 3 rotate的时候先first last offset i定好,然后从特殊的开始,行列感觉走 比如一列就是[first][last-offset]
//bytes, write a method to rotate the image by 90 degrees Can you do this in place?
//int 4 byte!!!
#include<iostream>
#include<string>
using namespace std;
#define N 10
struct matrix
{
int pixel[N][N];//declaration
};
//1 int 4 bytes
//2 layer,先编出基本的(最边上),然后用变量代替
//3 from corner
void rotateInPlace(matrix &m)
{
int top;
int first;
int last;
int offset;
for(int layer=0;layer<N/2;layer++)
{
first=layer;
last= N-1-first;
for(int i=first;i<last;i++)
{
offset=i-first;
//分四步
top=m.pixel[first+offset][first];
m.pixel[first+offset][first]=m.pixel[last][i];
m.pixel[last][i]=m.pixel[last-offset][last];
m.pixel[last-offset][last]=m.pixel[first][last-offset];
m.pixel[first][last-offset]=top;
}
}
}
void printMatrix(matrix m)
{ for(int j=0;j<N;j++)
{
for(int i=0;i<N;i++)
{
cout<<m.pixel[j][i]<<" ";
}
cout<<endl;
}
}
void main()
{
matrix *m=new matrix;
for(int j=0;j<N;j++)
{
for(int i=0;i<N;i++)
{
m->pixel[j][i]=j*10+i;
}
}
printMatrix(*m);
rotateInPlace(*m);
cout<<"after rotating once:"<<endl;
printMatrix(*m);
rotateInPlace(*m);
cout<<"after rotating twice:"<<endl;
printMatrix(*m);
}
//学习到的 1 in place 是不开辟新的空间
// 2 int就是4个 byte
// 3 rotate的时候先first last offset i定好,然后从特殊的开始,行列感觉走 比如一列就是[first][last-offset]