PTA 螺旋方阵

所谓“螺旋方阵”,是指对任意给定的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;
}
发布了23 篇原创文章 · 获赞 31 · 访问量 1117

猜你喜欢

转载自blog.csdn.net/weixin_45333771/article/details/103223747
今日推荐