编程算法 - 旋转矩阵 代码(C)

来源:互联网 发布:花千骨网络剧演员表 编辑:程序博客网 时间:2024/06/06 04:47

旋转矩阵 代码(C)


本文地址: http://blog.csdn.net/caroline_wendy


输出旋转矩阵, 使矩阵是按对角线螺旋上升, 在输出规则确定以后, 就可以判断, 上升规律是, 行列相加为定值.

所以采用两次循环的方法, 并且上下矩阵, 分开输出.

如:

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
  1.  1   2   6   7  15  
  2.  3   5   8  14  16  
  3.  4   9  13  17  22  
  4. 10  12  18  21  23  
  5. 11  19  20  24  25  

代码:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * main.cpp 
  3.  * 
  4.  *  Created on: 2014.6.12 
  5.  *      Author: Spike 
  6.  */  
  7.   
  8. /*eclipse cdt, gcc 4.8.1*/  
  9.   
  10. #include <stdio.h>  
  11.   
  12. void output(int n)  
  13. {  
  14.     if (n < 0) return;  
  15.   
  16.     const int MAX = 100;  
  17.     int a[MAX][MAX];  
  18.   
  19.     int min = 1;  
  20.     int max = n*n;  
  21.   
  22.     //上半个矩阵  
  23.     for (int i=0; i<n; i++) {  
  24.         for (int j=0; j<i+1; j++)  
  25.             if (i % 2 == 0) {  
  26.                 a[i-j][j] = min++;  
  27.                 a[n-1-i+j][n-1-j] = max--;  
  28.             } else {  
  29.                 a[j][i-j] = min++;  
  30.                 a[n-1-j][n-1-i+j] = max--;  
  31.             }  
  32.     }  
  33.   
  34.     for (int i=0; i<n; i++) {  
  35.         for (int j=0; j<n; j++)  
  36.             printf("%3d%c", a[i][j], j == n - 1 ? '\n' : ' ');  
  37.     }  
  38.   
  39. }  
  40.   
  41. int main()  
  42. {  
  43.     output(5);  
  44.     return 0;  
  45. }  


输出:

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
  1.  1   2   6   7  15  
  2.  3   5   8  14  16  
  3.  4   9  13  17  22  
  4. 10  12  18  21  23  
0 0
原创粉丝点击