1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
这种情况用模拟比较好推出,以1为坐标原点,一次递增,遇到边界则转向
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 100
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
const int intx[]=
{0,1,0,-1};
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
const int inty[]=
{1,0,-1,0};
int main()
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
int dir,i,j,n,data,x,y,nextx,nexty;
int arr[MAX_SIZE][MAX_SIZE];
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//*Read size*/
printf("please input the size\n");
scanf("%d",&n);
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//*Init*/
x= y= 0;
dir= 0;
memset(arr,0,sizeof(arr));
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//*fill*/
for(data=1; data<=n*n; data++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
arr[x][y]= data;
nextx= x+intx[dir];
nexty= y+inty[dir];
if(arr[nextx][nexty] || nextx>=n || nexty>=n || nextx<0 || nexty<0)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
dir++;
if(dir==4)dir=0;
}
x+= intx[dir];
y+= inty[dir];
}
for(i=0; i<n; i++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for(j=0; j<n; j++)
printf("%d\t",arr[i][j]);
printf("\n");
}
}
如果碰到另外一种情况就麻烦多了
21 22................
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
如果从中间开始模拟
从原点1开始,看方向的变化:右下左上;行走的步数:11223344……
公式:n^2= 1+1+2+2+...+n-1+n-1+n(第一种情况也有用到)
有了公式,那就可以先算出最大的data是多少,这样又转换为第一种方法了。
如果没有公式,单纯对行为进行模拟难度很大,不过还是可以实现的。
现在暂时还没有想到实现的方法,想到以后再补充吧。