“画布”(数据):二维数组
“画笔”(算法):(x,y)的坐标变换
算法:先判断再移动和“作画”。
判断是否越界,一开始的界是在n-1*n-1之内,之后逐渐减小。
#include <cstdio>
#include <iostream>#define maxn 10
using namespace std;
int a[maxn][maxn];
int main()
{
int n,x,y,tot=0;
cin>>n;
tot=a[x=0][y=n-1]=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(x=0; x<n; x++)
{
for(y=0; y<n; y++)
printf("%3d",a[x][y]);
putchar('\n');
}
return 0;
}
(1).while(tot<n*n)将横纵填数一直进行下去直到结束。
(2).像x+1<n这样的判断要在!a[x+1][y]之前,“&&”是短路运算符,如果x+1<n为假,将不会计算!a[x+1][y],a[x+1][y]也就不会访问非法内存了。