(1)八皇后与N皇后问题
八皇后问题是一个古老而著名的问题,是回溯算法的典型例题。该问题是十九世纪著名的数学家高斯1850年提出:在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。
八皇后问题可以推广到n皇后问题:
在n×n格的棋盘上放置彼此不受攻击的n个皇后。按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。n后问题等价于在n×n格的棋盘上放置n个皇后,任何2个皇后不放在同一行或同一列或同一斜线上。
(2)N皇后问题的编程实现
#include<iostream>
using namespace std;
/*
bool isLegal(int *Row,int CurrentColumn)--------判断当前坐标点(Row(CurrentColumn),CurrentColumn)是否符合要求
*/
bool isLegal(int *Row,int CurrentColumn)
{
for (int column = 1; column < CurrentColumn; column++)
if ((abs(CurrentColumn - column) == abs(Row[column] - Row[CurrentColumn])) || (Row[column] == Row[CurrentColumn]))return false;
return true;
}
/*
void Backtrack(int *Row,int n,int CurrentColumn,int &count)--------回溯,遍历排列树
input
int *Row-------------------行号,其数组元素Row[column]蕴含了棋盘上坐标点(Row[column],column)的行号和列号
int n----------------------Row的长度,即棋盘的大小为n*n
int CurrentColumn----------遍历至第CurrentColumn列,即当前列
int &count-----------------对符合要求的排列进行计数
*/
void Backtrack(int *Row,int n,int CurrentColumn,int &count)
{
//如果当前所在列CurrentColumn大于n,则计数使(count+1)并输出当前排列结果
if (CurrentColumn > n)
{
count++;
for (int column = 1; column <= n; column++)cout <<'('<< Row[column]<<','<<column<<')'<< ' ';
cout << endl;
}
else
//遍历当前列的每一行,若找到符合要求的点则遍历下一列
for (int row = 1; row <= n; row++)
{
Row[CurrentColumn] = row;
if(isLegal(Row, CurrentColumn))Backtrack(Row,n,CurrentColumn + 1,count);
}
}
int main()
{
int n,count=0;
cin >> n;
int *Row = new int[n];
for (int column = 0; column < n; column++)Row[column] = 0;
Backtrack(Row, n, 1, count);
cout << count << endl;
delete []Row;
return 0;
}
以八皇后问题为例,共有92方案,程序部分运行结果如下所示: