516. 神奇的幻方

题目链接

516. 神奇的幻方

幻方是一种很神奇的 \(N \times N\) 矩阵: 它由数字 \(1,2,3, \ldots, N \times N\) 构成,且每行、每列及两条对角线上的数 字之和都相同。
\(N\) 为奇数时,我们可以通过以下方法构建一个幻方:
首先将 1 写在第一行的中间。
之后,按如下方式从小到大依次填写每个数 \(K(K=2,3, \ldots, N \times N)\)

  1. \((K-1)\) 在第一行但不在最后一列,则将 \(K\) 填在最后一行, \((K-1)\) 所在列的右一列;
  2. \((K-1)\) 在最后一列但不在第一行,则将 \(K\) 填在第一列, \((K-1)\) 所在行的上一行;
  3. \((K-1)\) 在第一行最后一列,则将 \(K\) 填在 \((K-1)\) 的正下方;
  4. \((K-1)\) 既不在第一行,也不在最后一列,如果 \((K-1)\) 的右上方还末填数,则将 \(K\) 填在 \((K-1)\) 的 右上方,否则将 \(K\) 填在 \((K-1)\) 的正下方。

现给定 \(N\) ,请按上述方法构造 \(N \times N\) 的幻方。

输入格式

输入文件只有一行,包含一个整数 \(N\) ,即幻方的大小。

输出格式

输出文件包含 \(N\) 行,每行 \(N\) 个整数,即按上述方法构造出的 \(N \times N\) 的幻方。

数据范围

\(1≤N≤39\),\(N\) 为奇数。

输入样例:

3

输出样例:

8 1 6
3 5 7
4 9 2

解题思路

构造

对于奇数阶幻方,先在第一行中间放置 \(1\),再向右上方放置数,如果右上方已经有数了,向下方放数,考虑特殊情况,如果当前数在右上角,则向下方放数,如果数越界了,则向对面放数

  • 时间复杂度:\(O(n^2)\)

代码

// Problem: 神奇的幻方
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/518/
// Memory Limit: 16 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=40;
int n;
int a[N][N],t;
int main()
{
    cin>>n;
    int x=1,y=n/2+1;
    a[x][y]=++t;
    while(true)
    {
    	if(x==1&&y==n)
    	{
    		x++;
    		if(a[x][y])break;
    		a[x][y]=++t;
    	}
    	else
    	{
    		if(x==1)
    		{
    			y++;
    			x=n;
    			if(a[x][y])break;
    			a[x][y]=++t;
    		}
    		else if(y==n)
    		{
    			y=1;
    			x--;
    			if(a[x][y])break;
    			a[x][y]=++t;
    		}
    		else
    		{
    			if(a[x-1][y+1])
    			{
    				x++;
    				if(a[x][y])break;
    				a[x][y]=++t;
    			}
    			else
    			{
    				x--,y++;
    				a[x][y]=++t;
    			}
    		}
    	}
    }
    for(int i=1;i<=n;i++)
    	for(int j=1;j<=n;j++)cout<<a[i][j]<<(j<n?' ':'\n');
    return 0;
}
posted @ 2022-03-22 20:14  zyy2001  阅读(115)  评论(0编辑  收藏  举报