10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
代码:
- #include"iostream"
- #include"cmath"
- #include"string.h"
- using namespace std;
- #define max 10
- int a[max][max];
- int main()
- {
- int n,x,y,cot=1;
- scanf("%d",&n);
- memset(a,0,sizeof(a));
- a[x=0][y=n-1]=1;
- while(cot<n*n)
- {
- while(x+1<n && !a[x+1][y]) a[++x][y]=++cot;
- while(y-1>=0 && !a[x][y-1]) a[x][--y]=++cot;
- while(x-1>=0 && !a[x-1][y]) a[--x][y]=++cot;
- // cout<<a[x][y]<<endl;
- // break;
- while(y+1<n && !a[x][y+1]) a[x][++y]=++cot;
- }
- for(x=0;x<n;++x)
- {
- for(y=0;y<n;++y)
- printf("= ",a[x][y]);
- printf("\n");
- }
- return 0;
- }
第一次运行,没有出结果,依次用注释部分的检测代码,从大 while 循环外检测到内部,到第三个小 while 时,检测出了问题
需要注意的点很多,一定要认真。
另外值得注意的是:
&& 是短路运算符,因此,小 while 中的判断:把 a[x+1] 放在 && 之后,是有一定道理的,放在前面的话,当 x=n-1 时,x+1=n,数组访问非法地址;放在后面,前面的判断就决定了 x+1
来源: http://www.bubuko.com/infodetail-2453616.html