洛书(九宫)
给出1,2,3,……,9,这9个数字,请将他们排成一个三行三列的数字方阵,它的每行,每列和每个对角线上三个数字之和都相等。
这里我写了一个思路比较简单的方法(C#)
public static void JiuGong()
{
//默认格式为:
// n1,n2,n3
// n4,n5,n6
// n7,n8,n9
int i = 0;
for (int n1 = 1; n1 <= 9; n1++)
{
for (int n2 = 1; n2 <= 9; n2++)
{
for (int n3 = 1; n3 <= 9; n3++)
{
for (int n4 = 1; n4 <= 9; n4++)
{
for (int n5 = 1; n5 <= 9; n5++)
{
for (int n6 = 1; n6 <= 9; n6++)
{
for (int n7 = 1; n7 <= 9; n7++)
{
for (int n8 = 1; n8 <= 9; n8++)
{
for (int n9 = 1; n9 <= 9; n9++)
{
if (n1 + n2 + n3 == 15
&& n4 + n5 + n6 == 15
&& n7 + n8 + n9 == 15
&& n1 + n4 + n7 == 15
&& n2 + n5 + n8 == 15
&& n3 + n6 + n9 == 15
&& n1 + n5 + n9 == 15
&& n3 + n5 + n7 == 15
&& n1 != n2
&& n1 != n3
&& n1 != n4
&& n1 != n5
&& n1 != n6
&& n1 != n7
&& n1 != n8
&& n1 != n9
&& n2 != n3
&& n2 != n4
&& n2 != n5
&& n2 != n6
&& n2 != n7
&& n2 != n8
&& n2 != n9
&& n3 != n4
&& n3 != n5
&& n3 != n6
&& n3 != n7
&& n3 != n8
&& n3 != n9
&& n4 != n5
&& n4 != n6
&& n4 != n7
&& n4 != n8
&& n4 != n9
&& n5 != n6
&& n5 != n7
&& n5 != n8
&& n5 != n9
&& n6 != n7
&& n6 != n8
&& n6 != n9
&& n7 != n8
&& n7 != n9
&& n8 != n9
)
{
i++;
Console.WriteLine("第{0}组排列方式", i);
Console.WriteLine(n1 + " " + n2 + " " + n3);
Console.WriteLine(n4 + " " + n5 + " " + n6);
Console.WriteLine(n7 + " " + n8 + " " + n9);
Console.WriteLine();
}
}
}
}
}
}
}
}
}
}
Console.Read();
}
结果显示为: