所谓“螺旋方阵”,是指对任意给定的N,将1到N×N的数字从左上角第1个格子开始,按顺时针螺旋方向顺序填入N×N的方阵里。本题要求构造这样的螺旋方阵。
输入格式:
输入在一行中给出一个正整数N(<10)。
输出格式:
输出N×N的螺旋方阵。每行N个数字,每个数字占3位。
输入样例:
5
输出样例:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
#include <iostream>
using namespace std;
#include <string.h>
#define maxn 10
int a[maxn][maxn];
int main() {
int N, x, y, tot = 0;
cin >> N;
memset(a, 0, sizeof(a));
tot = a[x = 0][y = 0] = 1;
while (tot < N * N) {
while (x + 1 < N && !a[x + 1][y])a[++x][y] = ++tot;
while (y - 1 >= 0 && !a[x][y - 1])a[x][--y] = ++tot;
while (x - 1 >= 0 && !a[x - 1][y])a[--x][y] = ++tot;
while (y + 1 < N && !a[x][y + 1])a[x][++y] = ++tot;
}
for (y = 0;y < N;y++) {
for (x = 0;x < N;x++) {
if (a[x][y] < 10)cout << " " << a[x][y];
else cout << " " << a[x][y];
}
cout << "\n";
}
return 0;
}