小明最近在教邻居家的小朋友小学奥数,而最近正好讲述到了三阶幻方这个部分。
三阶幻方指的是将1~9不重复的填入一个33的矩阵当中,使得每一行、每一列和每一条对角线的和都是相同的。
三阶幻方又被称作九宫格,在小学奥数里有一句非常有名的口诀:
“二四为肩,六八为足,左三右七,戴九履一,五居其中”,
通过这样的一句口诀就能够非常完美的构造出一个九宫格来。
4 9 2
3 5 7
8 1 6
有意思的是,所有的三阶幻方,都可以通过这样一个九宫格进行若干镜像和旋转操作之后得到。
现在小明准备将一个三阶幻方(不一定是上图中的那个)中的一些数抹掉,交给邻居家的小朋友来进行还原,并且希望她能够判断出究竟是不是只有一个解。
而你呢,也被小明交付了同样的任务,但是不同的是,你需要写一个程序~
输入
输入一个33的矩阵,其中为0的部分表示被小明抹去的部分。
对于100%的数据,满足给出的矩阵至少能还原出一组可行的三阶幻方。
输出
如果仅能还原出一组可行的三阶幻方,则将其输出,否则输出“Too Many”(不包含引号)。
样例输入 Copy
0 7 2
0 5 0
0 3 0
样例输出 Copy
6 7 2
1 5 9
8 3 4
全排列匹配,对1 ~9 ,9个数进行全排列,当遇到原数组有不为0的,并且与排列的数不同的,说明不满足要求,continue
#include <iostream>
#include <algorithm>
using namespace std;
int a[10] = {1,2,3,4,5,6,7,8,9};
int b[10],temp[10],t[10];
int cnt;
int main()
{
for (int i =0 ; i < 9 ; i ++) cin >> b[i];
do
{
bool flag1 =false;
for (int i = 1; i <= 9 ; i ++)
{
if (b[i] && b[i] != a[i])
{
flag1 = true;
break;
}
}
if (flag1) 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(x 1== x2 && x2 == x3)
{
if(x3 == y1 && y1 == y2 && y2 == y3)
{
if(y3 == m && m == n)
{
cnt ++;
for(int i = 0 ; i < 9 ; i ++)
temp[i] = a[i];
}
}
}
}while (next_permutation(a,a + 9));
if (cnt == 1)
{
for (int i = 0 ; i < 9 ; i ++)
{
cout << temp[i] << ' ';
if ((i + 1) % 3 == 0) cout << endl;
}
}
else puts("Too Many");
return 0;
}
DFS:
把9个数读入到a[i]中去,每读入一个数,就标记一下这个数是否为0,是否使用过;
dfs(1)从第一个位置还是深搜,
如果cnt > 1,返回,如果st[x]这个位置的数不为0,不用填数字,dfs下一层;
枚举1~9,9个数,如果这个数没有被用过,就把这个数填进去;
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 15;
int a[N],b[N],ans[N];
bool st[N],used[N];
int cnt;
void check()
{
b[1] = a[1] + a[2] + a[3];
b[2] = a[4] + a[5] + a[6];
b[3] = a[7] + a[8] + a[9];
b[4] = a[1] + a[4] + a[7];
b[5] = a[2] + a[5] + a[8];
b[6] = a[3] + a[6] + a[9];
b[7] = a[1] + a[5] + a[9];
b[8] = a[3] + a[5] + a[7];
for (int i = 1 ; i <= 8 ; i ++) if (b[i] != 15) return;
cnt ++;
for (int i = 1 ; i <= 9 ; i ++) ans[i] = a[i];
}
void dfs(int x) //当前在第x个位置
{
if (cnt > 1) return;
if (x > 9)
{
check();
return;
}
if (st[x]) //当前这个位置已经有不为0的数字
{
dfs(x + 1);
return;
}
for (int i = 1 ; i <= 9 ; i ++)
{
if (!used[i])
{
a[x] = i;
used[i] = true;
dfs(x + 1);
used[i] = false;
}
}
}
int main()
{
for ( int i = 1 ; i <= 9 ; i ++)
{
cin >> a[i];
if (a[i])
{
st[i] = true;//标记i这个位置的数不为0
used[a[i]] = true; //标记a[i]这个数已经被用过
}
}
dfs(1);//从第一个位置开始深搜
if (cnt == 1)
{
for (int i = 1; i <= 9 ; i ++)
{
cout << ans[i] <<' ';
if (i % 3 == 0) cout << endl;
}
}
else puts("Too Many");
return 0;
}