careerCup1.6(没有do in place)

 //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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值