正看Matrix67书里的一节叫幻方之幻,提及了幻方这个东西。(3*3方格,每行之和 = 每列之和 = 对角线之和)

例如这个就是一个幻方:

8 1 6

3 5 7

4 9 2


幻方有一个奇妙性质:各行所组成的三位数的平方和,等于各行逆序所组成的三位数平方和。以前真不知道。

对于上图就有,816^2 + 357^2 + 492 ^2 = 618^2 + 753^2 + 294^2


闲来无聊,编了个程把所有幻方找出来了....一共就8个,

如下:




以下源码,随手写的,完全没有优化.....

#include <iostream>
using namespace std;

int a[3][3];
bool b[10];//b[i] == true 表示i可用

bool check()//检测是否满足幻方性质
{
	int i;
	int ch = a[0][0] + a[0][1] + a[0][2];

	for(i =1; i<3; i++)
		if((a[i][0]+a[i][1]+a[i][2]) != ch)
			return false;
	for(i=0; i<3; i++)
		if((a[0][i]+a[1][i]+a[2][i])!=ch)
			return false;
	if((a[0][0] + a[1][1] + a[2][2]) != ch)
		return false;
	if((a[0][2] + a[1][1] + a[2][0]) != ch)
		return false;
	return true;
}

void dfs(int arr[][3], int n)//深搜寻找可行解
{
	int k;
	for(k=1;k<=9;k++)
	{
		if(b[k])
		{
			arr[(n-1)/3][(n-1)%3] = k;
			b[k] = false;
			if(n == 9)	
			{
				if(check())
				{
					int tmp;
					for(tmp = 0;tmp<=2; tmp++)
						cout << arr[tmp][0] << '\t' << arr[tmp][1] << '\t' << arr[tmp][2] << '\n';
					cout << '\n';
				}
			}
			else
			{
				dfs(arr,n+1);
			}
			b[k] = true;
		}
	}
}

int main()
{
	int i;
	for(i=1;i<=9;i++)
		b[i] = true;

	dfs(a,1);

	return 0;
}



posted on 2012-11-10 22:19  zyearn  阅读(1063)  评论(0编辑  收藏  举报