[蓝桥杯2017初赛]九宫幻方

题目描述

小明最近在教邻居家的小朋友小学奥数,而最近正好讲述到了三阶幻方这个部分。
三阶幻方指的是将1~9不重复的填入一个3*3的矩阵当中,使得每一行、每一列和每一条对角线的和都是相同的。
三阶幻方又被称作九宫格,在小学奥数里有一句非常有名的口诀:
“二四为肩,六八为足,左三右七,戴九履一,五居其中”,
通过这样的一句口诀就能够非常完美的构造出一个九宫格来。
4 9 2
3 5 7
8 1 6
有意思的是,所有的三阶幻方,都可以通过这样一个九宫格进行若干镜像和旋转操作之后得到。
现在小明准备将一个三阶幻方(不一定是上图中的那个)中的一些数抹掉,交给邻居家的小朋友来进行还原,并且希望她能够判断出究竟是不是只有一个解。
而你呢,也被小明交付了同样的任务,但是不同的是,你需要写一个程序~

输入

输入一个3*3的矩阵,其中为0的部分表示被小明抹去的部分。
对于100%的数据,满足给出的矩阵至少能还原出一组可行的三阶幻方。

输出

如果仅能还原出一组可行的三阶幻方,则将其输出,否则输出“Too Many”(不包含引号)。

样例输入

0 7 2
0 5 0
0 3 0

样例输出

6 7 2
1 5 9
8 3 4

#include<iostream>
#include<string>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<map>
#include<stack>
#define ll long long
using namespace  std;
int a[9]={1,2,3,4,5,6,7,8,9};
int b[9],temp[9];
int main()
{
    int ans=0;
    for(int i=0;i<9;i++)
        cin>>b[i];
        
    do
    {
        int flag=0;
        for(int i=0;i<9;i++)
        {
            if(b[i]!=0)
            {
                if(a[i]!=b[i])
                {
                    flag=1;
                    break;
                }
            }
        }
        if(flag==1)
            continue;
        
        int x1=a[0]+a[1]+a[2];
        int x2=a[3]+a[4]+a[5];
        int x3=a[6]+a[7]+a[8];
 
        int y1=a[0]+a[3]+a[6];
        int y2=a[1]+a[4]+a[7];
        int y3=a[2]+a[5]+a[8];
 
        int m=a[0]+a[4]+a[8];
        int n=a[2]+a[4]+a[6];
        if(x1==x2&&x2==x3)
        {
            if(x3==y1&&y1==y2&&y2==y3)
            {
                if(y3==m&&m==n)
                {
                    ans++;
                    for(int i=0;i<9;i++)
                        temp[i]=a[i];
                }
            }
        }
 
    }while(next_permutation(a,a+9));
    //cout<<ans<<endl;
    if(ans==1)
    {
        cout<<temp[0]<<' '<<temp[1]<<' '<<temp[2]<<endl;
        cout<<temp[3]<<' '<<temp[4]<<' '<<temp[5]<<endl;
        cout<<temp[6]<<' '<<temp[7]<<' '<<temp[8]<<endl;
    }
    else
        cout<<"Too Many"<<endl;
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/-citywall123/p/12343663.html