附注:刚反应过来就是原题(回旋矩阵)的变种,从里到外和从外到里没有本质区别,囧
前段时间碰到一个题目
生成如下矩阵
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
代码如下:
- #include <stdio.h>
-
#include <assert.h>
-
-
enum direction {LEFT, RIGHT, DOWN, UP};
-
struct adjust{
-
int x;
-
int y;
-
};
-
struct adjust adjust[UP + 1] = {
-
{0, -1},
-
{0, 1},
-
{1, 0},
-
{-1, 0}
-
};
-
-
enum{ TURN_AROUNDS = 5, MAX_ROW = 20};
-
struct one_dir {
-
enum direction dir;
-
int steps;
-
};
-
struct one_dir actions[TURN_AROUNDS] = {
-
{UP, 1},
-
{RIGHT, 1},
-
{DOWN, 2},
-
{LEFT, 2},
-
{UP, 2}
-
};
-
int matrix[MAX_ROW][MAX_ROW];
-
-
void adjust_action_steps( )
-
{
-
int i;
-
-
for(i = 1; i < TURN_AROUNDS; i++)
-
actions[i].steps += 2;
-
}
-
-
int main(void)
-
{
-
int i, j, k, cur_row, cur_col;
-
int n;
-
int value = 1;
-
-
scanf("%d", &n);
-
assert(n <= MAX_ROW && n % 2 == 1);
-
-
cur_row = cur_col = n / 2;
-
matrix[cur_row][cur_col] = value++;
-
-
for(i = 1; i < n; i += 2){
-
for(j = 0; j < TURN_AROUNDS; j++){
-
for(k = 0; k < actions[j].steps; k++){
-
int dir = actions[j].dir;
-
-
cur_row += adjust[dir].x;
-
cur_col += adjust[dir].y;
-
matrix[cur_row][cur_col] = value++;
-
}
-
}
-
adjust_action_steps();
-
}
-
-
for(i = 0; i < n; i++){
-
for(j = 0 ; j < n; j++)
-
printf("%-4d", matrix[i][j]);
-
printf("\n");
-
}
-
}
如果生成如下的矩阵
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}
};
所以本人的解法弹性较好
阅读(952) | 评论(0) | 转发(0) |