逆时针转圈,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;
}
}