【本文鏈接】
http://www.cnblogs.com/hellogiser/p/eight-queens-puzzle.html
【題目】
在8×8的國際象棋上擺放八個皇後,使其不能相互攻擊,即任意兩個皇後不得處在同一行、同一列或者同一對角斜線上。下圖中的每個黑色格子表示一個皇後,這就是一種符合條件的擺放方法。請求出總共有多少種擺法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// 54_EightQueensPuzzle.cpp : Defines the entry point for the console application.
//
/*
version: 1.0
author: hellogiser
blog: http://www.cnblogs.com/hellogiser
date: 2014/5/24
*/
#include "stdafx.h"
#include <iostream>
using namespace std;
#define N 8
int m_nPermutationCount = 0;
int m_nValidCount = 0;
// swap a and b
void Swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
// check whether pos array is valid
bool CheckValid(int *pos, int n)
{
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; j++)
{
//only need to check whether pos[i] and pos[j] are on diagonal
if (i - j == pos[i] - pos[j] || j - i == pos[i] - pos[j])
{
return false;
}
}
}
return true;
}
// print pos array
void Print(int *pos, int n)
{
for (int i = 0; i < n; ++i)
printf("%d ", pos[i]);
}
void Permutation(int *pos, int n, int index)
{
m_nPermutationCount++;
if (index == n)
{
// this permutation generated
if (CheckValid(pos, n))
{
// valid permutation
m_nValidCount++;
//Print(pos,n);
}
}
else
{
for (int i = index; i < n; ++i)
{
Swap(pos[index], pos[i]);
Permutation(pos, n, index + 1);
Swap(pos[index], pos[i]);
}
}
}
void EightQueensPuzzle()
{
// init pos
int pos[N];
for (int i = 0; i < N; i++)
{
pos[i] = i;
}
Permutation(pos, N, 0);
}
void test_main()
{
EightQueensPuzzle();
cout << m_nPermutationCount << endl;
cout << m_nValidCount << endl; //92
}
int _tmain(int argc, _TCHAR *argv[])
{
test_main();
return 0;
}
【參考】
http://www.cnblogs.com/hellogiser/p/3738844.html
http://zhedahht.blog.163.com/blog/static/2541117420114331616329/
http://en.wikipedia.org/wiki/Eight_queens_puzzle
http://blog.csdn.net/hackbuteer1/article/details/6657109
【本文鏈接】
http://www.cnblogs.com/hellogiser/p/eight-queens-puzzle.html