#include?<iostream>
using?namespace?std;
int?main(int?argv,char?*argc[]){
int?n,m,i,t,x,*q,**p;
cout?<<?"Input?n(int?1~20)...\nn=";
if(!(cin?>>?n)?||?n<1?||?n>20){
cout?<<?"Input?error,?redo:?";
return?0;
}
q=new?int[n*n];
if(q==NULL?||?(p=new?int?*[n])==NULL){
cout?<<?"Application?memory?failure...\n";
return?0;
}
for(t=i=0;i<n;p[i++]=q+t,t+=n);
for(m=n>>1,t=x=1;t<=m;t++){//形成順旋
for(i=t-1;i<n-t;i++)//上至下
p[i][n-t]=x++;
for(i=n-t;i>=t;i--)//右至左
p[n-t][i]=x++;
for(i=n-t;i>=t;i--)//下至上
p[i][t-1]=x++;
for(i=t-1;i<n-t;i++)//左至右
p[t-1][i]=x++;
}
if(n&1)//奇數時處理最後壹個數
p[t=n>>1][t]=x;
cout.fill('?');
for(i=0;i<n;i++){
for(t=0;t<n;t++){
cout.width(4);
cout?<<?p[i][t];
}
cout?<<?endl;
}
delete?[]q;
delete?[]p;
return?0;?
}
運行樣例: