优美的螺旋方阵:
所谓“螺旋方阵”,是指对任意给定的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<stdio.h>
int main(void) {
int n,i,j;
int a[10][10];
scanf("%d", &n);
int x = 0, y = 0;
int k = 1;
int bound0=n-1, bound1=n-1, bound2=0, bound3=1;
int direction = 0;//0向右,1向下,2向左,3向上
while(k<=n*n){
if(direction==0){
a[x][y++] = k++;
if (y == bound0) {//向右走,遇到墙壁就向下
direction = 1;
bound0--;
}
} else if (direction == 1) {
a[x++][y] = k++;
if (x == bound1) {//向下走,遇到墙壁就向左
direction = 2;
bound1--;
}
} else if (direction == 2) {
a[x][y--] = k++;
if (y == bound2) {//向左走,遇到墙壁就向上
direction = 3;
bound2++;
}
} else if(direction == 3)
{
a[x--][y] = k++;
if (x == bound3) {//向上走,遇到墙壁就向右
direction = 0;
bound3++;
}
}
}
for( i=0;i<n;i++){
for(j=0;j<n;j++){
printf(" %2d",a[i][j]);
}
printf("\n");
}
return 0;
}