問題描述
八皇后問題,是一個古老而著名的問題,是回溯算法的典型案例。該問題是國際西洋棋棋手馬克斯·貝瑟爾於1848年提出:在8×8格的國際象棋上擺放八個皇后,使其不能互相攻擊,即任意兩個皇后都不能處於同一行、同一列或同一斜線上,問有多少種擺法.
思路
本題採用回溯遞歸求解,從第一行開始選擇擺放位置,這樣就避免了橫向衝突,然後每次放置皇后只要檢驗是否存在縱向衝突或斜向衝突。
code
#include <iostream>
using namespace std;
const int n = 8;
int result[10];
int cnt;
void slove(int cur)
{
if(cur == n)
{
//打印結果
cout << "#" << cnt ++ << ": ";
for(int i = 0; i < n; i ++)
{
cout << "(" << i << ", " << result[i] << ") ";
}
cout << endl;
}
else
{
for(int i = 0; i < n; i ++)
{
//選擇在第cur行第列放置
result[cur] = i;
bool ok = true;
for(int j = 0; j < cur; j ++)
{
//檢測是否與之前放置的皇后存在斜向或者縱向衝突
if(result[cur]-result[j] == cur-j || result[j]-result[cur] == cur-j || result[cur] == result[j] )
{
ok = false;
break;
}
}
if(ok)
{
//沒衝突時遞歸向下一行求解
slove(cur+1);
}
}
}
}
int main()
{
slove(0);
return 0;
}