将矩阵旋转90度:
题目描述:
例如将一个5*5的矩阵顺时针旋转90度:旋转前
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
选转后:
21 16 11 6 1
22 17 12 7 2
23 18 13 8 3
24 19 14 9 4
25 20 15 10 5
分析:如果N是偶数,则矩阵构成N/2圈;如果N是奇数,则矩阵构成(N-1)/2 圈;
将矩阵顺时针旋转90度,就是将每圈的元素在4个方位依次轮换位置:
交换元素的公式如下:
ai,j ------------->aj,N-i+1
↑ ↓
↑ ↓
aN-j+1 ---------->aN-i+1,N-j+1
代码如下:
1 /* */ 2 # include <iostream> 3 # include <cstdio> 4 # include <iomanip> 5 using namespace std; 6 7 int main() 8 { 9 int a[20][20], i, j, p=1, t, n; 10 printf("请输入矩阵的阶: "); 11 scanf("%d", &n); 12 printf("*******旋转前的矩阵******* "); 13 for( i=1; i<=n; i++ ) 14 { 15 for( j=1; j<=n; j++ ) 16 { 17 a[i][j] = p++; 18 printf("%4d", a[i][j]); 19 } 20 printf(" "); 21 } 22 printf("*******顺时针旋转后的矩阵******* "); 23 for( i=1; i<=n/2; i++ ) 24 { 25 for( j=i; j<n-i+1; j++ ) 26 { 27 t = a[i][j]; 28 a[i][j] = a[n-j+1][i]; 29 a[n-j+1][i] = a[n-i+1][n-j+1]; 30 a[n-i+1][n-j+1] = a[j][n-i+1]; 31 a[j][n-i+1] = t; 32 } 33 } 34 for( i=1; i<=n; i++ ) 35 { 36 for( j=1; j<=n; j++ ) 37 { 38 printf("%4d", a[i][j]); 39 } 40 printf(" "); 41 } 42 return 0; 43 }