#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int a[20][20];
int n,i = 0;
memset(a,0,sizeof(a)); //通过memset函数实现对数组内的元素作统一的处理!
scanf("%d",&n);
int number = 1;
int x = 0,y = n-1;
a[x][y] = 1;
while (number < n*n) //最大的数就是n*n
{
while (x < n-1 && !a[x+1][y]) a[++x][y] = ++number;/*防止越界,而且不用考虑是否超过了数组定义的范围,因为有x < n-1这一判断!*/
while (y-1 >= 0 && !a[x][y-1]) a[x][--y] = ++number;
while (x-1 >= 0 && !a[x-1][y]) a[--x][y] = ++number;
while (y+1 < n && !a[x][y+1]) a[x][++y] = ++number;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
return 0;
}
输出结果:
6
16 17 18 19 20 1
15 30 31 32 21 2
14 29 36 33 22 3
13 28 35 34 23 4
12 27 26 25 24 5
11 10 9 8 7 6
题目并不是很难,最重要的是此题的思维方式值得借鉴!通过对界的控制从而实现每次赋值不重复不多余!