思路
简单模拟,确定1的位置,根据四条规则,就可以求出整个矩阵了。
代码
#include<cstdio>
using namespace std;
int n,a[40][40],temp1=1,temp2;//初始化
int main()
{
scanf("%d",&n);//读入
a[1][n/2+1]=1;//确定1的位置
temp2=n/2+1;//算出边界
for (int i=2;i<=n*n;i++)
{
if (temp1==1&&temp2!=n)//如果是符合第一条规则
{
a[n][temp2+1]=i;
temp1=n;
temp2+=1;
}
else if (temp1!=1&&temp2==n)//如果是符合第二条规则
{
a[temp1-1][1]=i;
temp1-=1;
temp2=1;
}
else if (temp1==1&&temp2==n)//如果是符合第三条规则
{
a[temp1+1][temp2]=i;
temp1+=1;
}
else if (a[temp1-1][temp2+1]==0)//如果符合第四条规则的第一种
{
a[temp1-1][temp2+1]=i;
temp1-=1;
temp2+=1;
}
else
{
a[temp1+1][temp2]=i;
temp1+=1;
}
}
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
if (j!=n) printf("%d ",a[i][j]);//输出
else printf("%d",a[i][j]);//输出
if (i!=n) printf("\n");//输出
}
return 0;
}