所谓“螺旋方阵”,是指对任意给定的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 Num = 1;
int count = 0, i = 0, j = -1;
void Down(int x[10][10], int step) //向下输入
{
while (step)
{
i++;
x[i][j] = Num++;
step--;
}
count++;
}
void Up(int x[10][10], int step) //向上输入
{
while (step)
{
i--;
x[i][j] = Num++;
step--;
}
count++;
}
void Right(int x[10][10], int step) //向右输入
{
while (step)
{
j++;
x[i][j] = Num++;
step--;
}
count++;
}
void Left(int x[10][10], int step) //向左输入
{
while (step)
{
j--;
x[i][j] = Num++;
step--;
}
count++;
}
void Putnumber(int x[10][10], int N)
{
for (int i = 0; i < N; i++, printf("\n"))
for (int j = 0; j < N; j++)
printf("%3d", x[i][j]);
}
int main()
{
int N;
scanf("%d", &N);
int x[10][10] = {0};
int step = N; //行列变化的步数
int flag = 0;
while (step)
{
if (count % 2) //判定步数是否变化
step--;
switch (flag % 4)
{
case 0:
Right(x, step), flag++;
break;
case 1:
Down(x, step), flag++;
break;
case 2:
Left(x, step), flag++;
break;
case 3:
Up(x, step), flag++;
break;
default:
break;
}
}
Putnumber(x, N);
return 0;
}
昨天写到这个题,做了挺久,感觉是思路没对导致代码过于冗长
暂时不知道应该说些或者总结些什么,想到再更新吧