1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
#define matrix vector< vector<T> >
int WIDTH = 3;
//======================================================================
template <typename T> void print( const matrix &M )
{
for ( auto row : M )
{
for ( auto e : row ) cout << setw( WIDTH ) << e << ' ';
cout << '\n';
}
cout << '\n';
}
//======================================================================
template <typename T> matrix quarterTurns( const matrix &M, int q )
{ // Rotate a SQUARE matrix by q quarter turns clockwise
q = q % 4; // Effective number of quarter turns (0-3)
int N = M.size();
matrix R = M;
if ( q == 0 ) return R; // Identity
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
int ii, jj; // Indices that i and j map to in the rotated matrix
switch( q )
{
case 1: ii = j ; jj = N - 1 - i; break;
case 2: ii = N - 1 - i; jj = N - 1 - j; break;
case 3: ii = N - 1 - j; jj = i ; break;
}
R[ii][jj] = M[i][j];
}
}
return R;
}
//======================================================================
int main()
{
// vector< vector<int> > M = { { 1, 2, 3 },
// { 4, 5, 6 },
// { 7, 8, 9 } };
//
vector< vector<int> > M = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
for ( int q = 0; q < 4; q++ ) print( quarterTurns( M, q ) );
}
|