九宫幻方


    小明最近在教邻居家的小朋友小学奥数,而最近正好讲述到了三阶幻方这个部分,三阶幻方指的是将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<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<cmath>

typedef long long ll;
using namespace std;

int a[15];
int b[15];
int c[15];
int sum[10];
int main()
{
	int cnt1=0;
	for(int t=1;t<=9;t++)
	{
		scanf("%d",&b[t]);
		if(b[t]!=0)
		{
			cnt1++;
		}
	}
	for(int t=1;t<=9;t++)
	{
		a[t]=t;
	}
	int s=0;
	do
	{
		
		if(a[1]+a[2]+a[3]==a[4]+a[5]+a[6]&&a[4]+a[5]+a[6]==a[7]+a[8]+a[9]&&a[1]+a[2]+a[3]==a[1]+a[4]+a[7]&&a[1]+a[2]+a[3]==a[2]+a[5]+a[8]&&a[1]+a[2]+a[3]==a[3]+a[6]+a[9]&&a[1]+a[2]+a[3]==a[1]+a[5]+a[9]&&a[1]+a[2]+a[3]==a[3]+a[5]+a[7])
		{
			
			int cnt=0;
			for(int t=1;t<=9;t++)
			{
			   if(b[t]!=0&&b[t]==a[t])
			   {
			   	cnt++;
			   }	
			} 
			if(cnt==cnt1)
			{
				for(int t=1;t<=9;t++)
				{
					c[t]=a[t];
				}
				s++;
			}
		}
		if(s>=2)
		{
			break;
		}
	}while(next_permutation(a+1,a+10));
	if(s==1)
	{
		for(int t=1;t<=9;t++)
		{
			if(t%3>=1&&t%3<=2)
			cout<<c[t]<<" ";
			if(t%3==0)
			{
				cout<<c[t]<<endl;
			
			}
		}
	}
	else
	{
		cout<<"Too Many"<<endl;
	}
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/lbperfect123/article/details/88062207