所谓“螺旋方阵”,是指对任意给定的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 <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <cmath>
#include <cstring>
#include <deque>
#include <queue>
using namespace std;
#define ios \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
#define ll long long
#define met(a,b) memset(a,b,sizeof(a))
const int N = 1010;
int n,cnt,pd=1,one=1;
int arr[N][N];
int main(){
// freopen("D:\\YJ.txt","r",stdin);
cin>>n;
for(int i=1;i<=n/2+1;i++){
for(int j=one;j<=n-one+1;j++){
arr[i][j]=++cnt;
}
for(int j=i+1;j<=n-one+1;j++){
arr[j][n-i+1]=++cnt;
}
for(int j=n-i;j>=one;j--){
arr[n-i+1][j]=++cnt;
}
for(int j=n-i;j>=one+1;j--){
arr[j][i]=++cnt;
}
one++;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
printf("%3d",arr[i][j]);
}
printf("\n");
}
ios;
return 0;
}