测试数据有多组,处理到文件尾。每组测试数据的第一行输入2个整数n,m(1<n<20,1<=m<=100),接下来输入n行数据,每行n个整数。
例子:
3 1
4 9 2
3 5 7
8 1 6
变成
8 3 4
1 5 9
6 7 2
#include <algorithm>
template<typename T, size_t N>
void MatrixRotate( T (&matrix)[N][N] )
{
for( size_t r=0; r!=N/2; ++r )
{
for( size_t c=r; c+r+1!=N; ++c )
{
std::swap( matrix[r][c], matrix[N-1-c][r] );
std::swap( matrix[N-1-c][r], matrix[N-1-r][N-1-c] );
std::swap( matrix[N-1-r][N-1-c], matrix[c][N-1-r] );
}
}
}
#include <iostream>
using namespace std;
template<typename T, size_t R, size_t C>
void OutputMatrix( T (&matrix)[R][C] )
{
for( size_t i=0; i!=R*C; ++i )
cout << matrix[i/C][i%C] << " \n"[i%C==C-1];
}
int main( void )
{
int s1[1][1] = { 4 };
MatrixRotate( s1 );
OutputMatrix( s1 );
cout << "-------------\n";
int s2[2][2] = { 4, 9
, 3, 5 };
MatrixRotate( s2 );
OutputMatrix( s2 );
cout << "-------------\n";
int s3[3][3] = { 4, 9, 2
, 3, 5, 7
, 8, 1, 6 };
MatrixRotate( s3 );
OutputMatrix( s3 );
return 0;
}
例子:
3 1
4 9 2
3 5 7
8 1 6
变成
8 3 4
1 5 9
6 7 2
#include <algorithm>
template<typename T, size_t N>
void MatrixRotate( T (&matrix)[N][N] )
{
for( size_t r=0; r!=N/2; ++r )
{
for( size_t c=r; c+r+1!=N; ++c )
{
std::swap( matrix[r][c], matrix[N-1-c][r] );
std::swap( matrix[N-1-c][r], matrix[N-1-r][N-1-c] );
std::swap( matrix[N-1-r][N-1-c], matrix[c][N-1-r] );
}
}
}
#include <iostream>
using namespace std;
template<typename T, size_t R, size_t C>
void OutputMatrix( T (&matrix)[R][C] )
{
for( size_t i=0; i!=R*C; ++i )
cout << matrix[i/C][i%C] << " \n"[i%C==C-1];
}
int main( void )
{
int s1[1][1] = { 4 };
MatrixRotate( s1 );
OutputMatrix( s1 );
cout << "-------------\n";
int s2[2][2] = { 4, 9
, 3, 5 };
MatrixRotate( s2 );
OutputMatrix( s2 );
cout << "-------------\n";
int s3[3][3] = { 4, 9, 2
, 3, 5, 7
, 8, 1, 6 };
MatrixRotate( s3 );
OutputMatrix( s3 );
return 0;
}