1. 程式人生 > >四階幻方的窮舉求解.

四階幻方的窮舉求解.

速度太慢了,有時間研究構造四階幻方的構造法…..

#include "iostream"
#include "algorithm"
#include "queue"
#include "vector"
#include "list"
using namespace std;
bool isused[17] = { false };
int board[17];
queue<int>x;

#define M 34
void print(int count)
{
    cout << "case :" << count << endl;
    for
(size_t beg = 1; beg != 17; beg+=4) { cout << board[beg] << " \t" << board[beg + 1] << "\t " << board[beg + 2] << " \t" << board[beg + 3]<<endl; } cout<< "====================================" << endl; } bool
check() { if (board[13] + board[14] + board[15] + board[16] != M) return false; return board[1] + board[6] + board[11] + board[16] == M&& board[4] + board[7] + board[10] + board[13] == M ? true : false; } void func(int n) { static int index = 0; if (n == 17) { if
(check())//符合要求 print(++index); return; } if(n<=12) { int count = x.size(); while (--count!=-1)//使用佇列裡面現有的元素 { auto m = x.front(); x.pop(); board[n] = m; isused[m] = true; do { if (!(n % 4) && board[n] + board[n - 1] + board[n - 2] + board[n - 3] != M) break; if (n ==11 && board[n] + board[n - 1] + board[n - 4] + board[n - 5] != M) break; func(n + 1); } while (0); isused[m] = false; x.push(m); } } else { int m = M - board[n - 4] - board[n - 8] - board[n - 12]; if (m > 0 && m < 17 && !isused[m]) { board[n] = m; isused[m] = true; func(n + 1); isused[m] = false; } } } int main() { for (size_t i = 1; i != 17; ++i) x.push(i); func(1); return 0; }