例如 n=4
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#define maxn 20
using namespace std;
int a[maxn][maxn];
int main(){
int n,x,y,tot=1;//n正方形大小 x,y二维数组的坐标 tot填的数字从1开始;
scanf("%d",&n);
memset(a,0,sizeof(a));//初始化a数组
x=0;y=n-1;//蛇的初始位置
a[0][n-1]=1; //第一个位置的数字为1
//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中条件指 除 再走就出界&&再走就是走过的格子 之外
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]);}
printf("\n");
}
return 0;
}