洛谷P2615 神奇的幻方

题目传送门

( 不写算法题果然退步了。。。(╥╯^╰╥) )

代码如下:

#include<bits/stdc++.h>

using namespace std;
#define MAXN 1002
int arr[MAXN][MAXN];
void outPut(int n)
{
     bool f = false;
    for(int i=1; i<=n; i++)
    {
        f = false;
        for(int j=1; j<=n; j++)
        {
            if(f)
            {
                cout<<" ";
            }
            cout<<arr[i][j];
            f = true;
        }
        cout<<endl;
    }
}

bool ok1(int n,int k)
{
    bool ok = false;
    for(int i=1; i<n; i++)
    {
        if(arr[1][i] == k-1)
        {
            ok = true;
            arr[n][i+1] = k;
            break;
        }
    }

    return ok;
}
bool ok2(int n,int k)
{
    bool ok = false;
    for(int i=2; i<=n; i++)
    {
        if(arr[i][n] == k-1)
        {
            ok = true;
            arr[i-1][1] = k;
            break;
        }
    }
    return ok;
}
bool ok3(int n,int k)
{
    bool ok = false;
    if(arr[1][n] == k-1)
    {
        ok = true;
        arr[2][n] = k;
    }
    return ok;
}
void ok4(int n,int k)
{
    for(int i=2; i<=n; i++)
    {
        for(int j=1; j<n; j++)
        {
            if(arr[i][j] == k-1)
            {
          //      cout<<i<<" "<<j<<endl;
                if(arr[i-1][j+1] == 0)
                {
                    arr[i-1][j+1] = k;
                }else
                {
                    arr[i+1][j] = k;
                }
                break;
            }
        }
    }
    return ;
}
int main()
{
    int n;
    cin>>n;
    memset(arr,0,sizeof(arr));
    arr[1][n/2+1]=1;
    int k = 2;
    for(k=2; k<=n*n; k++)
    {
        if(ok1(n,k))
        {
  //          cout<<1<<endl;
            continue;
        }else if(ok2(n,k))
        {
   //         cout<<2<<endl;
            continue;
        }else if(ok3(n,k))
        {
    //        cout<<3<<endl;
            continue;
        }else
        {
    //        cout<<4<<endl;
            ok4(n,k);
        }
    }
    outPut(n);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38851184/article/details/108717261