careercup6

逆时针转圈,4个数为一组,由外到内一圈圈转。关键在于准确记录四个数的下标位置。用了六个小数组,当然四个也可以。

offset_x是用来记录初始位置。p,q记录每一圈开始时的偏移量,x,y记录在圈内转动循环时的偏移量。

/*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?
*/
#include <iostream>
#define N 4
using namespace std;

int main(){
	int mat[N][N] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
	int off_x[4] ={0,0,N-1,N-1}; //the initiate value of four groups in the beginning of every round
	int off_y[4] = {0,N-1,N-1,0};
	int p[4] = {1,1,-1,-1}; //the offset value in the beginning of every round;
	int q[4] = {1,-1,-1,1};
	int x[4] = {0,1,0,-1}; //the increase step
	int y[4] = {1,0,-1,0};

	for(int it = 0; it<N/2; it++)
		for(int begin = 0; begin<N-2*it-1; begin++){ //four points a group to rotate
			int temp = mat[it*p[0]+off_x[0]+begin*x[0]][it*q[0]+off_y[0]+begin*y[0]];
			for(int j =1; j<=3; j++)
				mat[it*p[j-1]+off_x[j-1]+begin*x[j-1]][it*q[j-1]+off_y[j-1]+begin*y[j-1]] = 
				mat[it*p[j]+off_x[j]+begin*x[j]][it*q[j]+off_y[j]+begin*y[j]];
			mat[it*p[3]+off_x[3]+begin*x[3]][it*q[3]+off_y[3]+begin*y[3]] = temp;	
		} 

	for(int i = 0; i<N; i++){
		for(int j = 0; j<N; j++)
			cout<<mat[i][j]<<" ";
		cout<<endl;
	} 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值