如何将一个行列为奇数的方阵旋转,如旋转90°
测试数据有多组,处理到文件尾。每组测试数据的第一行输入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; }
#include<stdio.h> #define N 5 int main() { int i,j; int s[N][N]={{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}}; printf("原始矩阵:\n"); for(i=0;i<N;i++) { for(j=0;j<N;j++) printf("%4d",s[i][j]); printf("\n"); } printf("\n\n旋转后矩阵:\n"); for(i=0;i<N;i++) { for(j=0;j<N;j++) printf("%4d",s[j][N-i-1]); printf("\n"); } return 0; }