NOIP2015 提高组 day1 神奇的幻方

直接贴代码

#include
#define MAXN 39
using namespace std;
int n,num;
int mat[MAXN+5][MAXN+5];
void solve(int x,int y)
{
	if(num==n*n)
		return;
	if(x==1&&y!=n)
	{
		mat[n][y+1]=++num;
		solve(n,y+1);
	}
	else if(x!=1&&y==n)
	{
		mat[x-1][1]=++num;
		solve(x-1,1);
	}
	else if(x==1&&y==n)
	{
		mat[x+1][y]=++num;
		solve(x+1,y);
	}
	else
	{
		if(mat[x-1][y+1]==0)
		{
			mat[x-1][y+1]=++num;
			solve(x-1,y+1);
		}
		else
		{
			mat[x+1][y]=++num;
			solve(x+1,y);
		}
	}
}
int main()
{
	freopen("magic.in","r",stdin);
	freopen("magic.out","w",stdout);
	int i,j;
	scanf("%d",&n);
	mat[1][(n+1)/2]=++num;
	solve(1,(n+1)/2);
	for(i=1;i<=n;i++)
		for(j=1;j<=n;j++)
			printf("%d%c",mat[i][j],j==n?'\n':' ');
}

你可能感兴趣的:(NOIP2015 提高组 day1 神奇的幻方)