题解
2024-10-03 11:30:41
发布于:广东
6阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
int a[40][40]; //填数方格
int main()
{
    int n;
    cin >> n;
    a[1][n/2+1]=1;
    map<int,pair<int,int>> m; //位置
    m[1]={1,n/2+1};
    for (int i=2;i<=n*n;i++)
    {
        if (m[i-1].first==1 && m[i-1].second!=n)
        {
            a[n][m[i-1].second+1]=i;
            m[i]={n,m[i-1].second+1}; //记录位置
        }
        else if (m[i-1].first!=1 && m[i-1].second==n)
        {
            a[m[i-1].first-1][1]=i;
            m[i]={m[i-1].first-1,1};
        }
        else if (m[i-1].first==1 && m[i-1].second==n)
        {
            a[m[i-1].first+1][m[i-1].second]=i;
            m[i]={m[i-1].first+1,m[i-1].second};
        }
        else if (m[i-1].first!=1 && m[i-1].second!=n)
        {
            if (a[m[i-1].first-1][m[i-1].second+1]==0)
            {
                a[m[i-1].first-1][m[i-1].second+1]=i;
                m[i]={m[i-1].first-1,m[i-1].second+1};
            }
            else
            {
                a[m[i-1].first+1][m[i-1].second]=i;
                m[i]={m[i-1].first+1,m[i-1].second};
            }
        }
    }
    for (int i=1;i<=n;i++)
    {
        for (int j=1;j<=n;j++)
            cout << a[i][j] << ' ';
        cout << endl;
    }
	return 0;
}
这里空空如也





有帮助,赞一个