Chinaunix首页 | 论坛 | 博客
  • 博客访问: 590422
  • 博文数量: 197
  • 博客积分: 7001
  • 博客等级: 大校
  • 技术积分: 2155
  • 用 户 组: 普通用户
  • 注册时间: 2005-02-24 00:29
文章分类

全部博文(197)

文章存档

2022年(1)

2019年(2)

2015年(1)

2012年(100)

2011年(69)

2010年(14)

2007年(3)

2005年(7)

分类: C/C++

2011-01-26 11:13:57

附注:刚反应过来就是原题(回旋矩阵)的变种,从里到外和从外到里没有本质区别,囧

前段时间碰到一个题目
生成如下矩阵
n=3
1 2 3
8 9 4 
7 6 5

设计出如下题目,美中不足的要求行列相等,最早的没有那个要求
输入一奇数n,生成如下矩阵
n=3
9   2   3   
8   1   4   
7   6   5   

n=5
25  10  11  12  13  
24  9   2   3   14  
23  8   1   4   15  
22  7   6   5   16  
21  20  19  18  17 

n=9

81  50  51  52  53  54  55  56  57  
80  49  26  27  28  29  30  31  58  
79  48  25  10  11  12  13  32  59  
78  47  24  9   2   3   14  33  60  
77  46  23  8   1   4   15  34  61  
76  45  22  7   6   5   16  35  62  
75  44  21  20  19  18  17  36  63  
74  43  42  41  40  39  38  37  64  
73  72  71  70  69  68  67  66  65 

代码如下:

  1. #include <stdio.h>
  2. #include <assert.h>

  3. enum direction {LEFT, RIGHT, DOWN, UP};
  4. struct adjust{
  5.     int x;
  6.     int y;
  7. };
  8. struct adjust adjust[UP + 1] = {
  9.         {0, -1},
  10.         {0, 1},
  11.         {1, 0},
  12.         {-1, 0}
  13. };

  14. enum{ TURN_AROUNDS = 5, MAX_ROW = 20};
  15. struct one_dir {
  16.     enum direction dir;
  17.     int steps;
  18. };
  19. struct one_dir actions[TURN_AROUNDS] = {
  20.     {UP, 1},
  21.     {RIGHT, 1},
  22.     {DOWN, 2},
  23.     {LEFT, 2},
  24.     {UP, 2}
  25. };
  26. int matrix[MAX_ROW][MAX_ROW];

  27. void adjust_action_steps( )
  28. {
  29.     int i;

  30.     for(i = 1; i < TURN_AROUNDS; i++)
  31.         actions[i].steps += 2;
  32. }

  33. int main(void)
  34. {
  35.     int i, j, k, cur_row, cur_col;
  36.     int n;
  37.     int value = 1;

  38.     scanf("%d", &n);
  39.     assert(n <= MAX_ROW && n % 2 == 1);

  40.     cur_row = cur_col = n / 2;
  41.     matrix[cur_row][cur_col] = value++;

  42.     for(i = 1; i < n; i += 2){
  43.         for(j = 0; j < TURN_AROUNDS; j++){
  44.             for(k = 0; k < actions[j].steps; k++){
  45.                 int dir = actions[j].dir;

  46.                 cur_row += adjust[dir].x;
  47.                 cur_col += adjust[dir].y;
  48.                 matrix[cur_row][cur_col] = value++;
  49.             }
  50.         }
  51.         adjust_action_steps();
  52.     }

  53.     for(i = 0; i < n; i++){
  54.         for(j = 0 ; j < n; j++)
  55.             printf("%-4d", matrix[i][j]);
  56.         printf("\n");
  57.     }
  58. }
如果生成如下的矩阵
5   6   7  
4   1   8  
3   2   9  

17  18  19  20  21 
16  5   6   7   22 
15  4   1   8   23 
14  3   2   9   24 
13  12  11  10  25 

只须调整
struct one_dir actions[TURN_AROUNDS] = {
    {DOWN, 1},
    {LEFT, 1},
    {UP, 2},
    {RIGHT, 2},
    {DOWN, 2}
};

所以本人的解法弹性较好

阅读(892) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~