八皇后問題是什麼:
八皇后問題,是一個古老而著名的問題,是回溯算法的典型案例。該問題是國際西洋棋棋手馬克斯·貝瑟爾於1848年提出:在8×8格的國際象棋上擺放八個皇后,使其不能互相攻擊,即任意兩個皇后都不能處於同一行、同一列或同一斜線上,問有多少種擺法。
高斯認爲有76種方案。1854年在柏林的象棋雜誌上不同的作者發表了40種不同的解,後來有人用圖論的方法解出92種結果。計算機發明後,有多種計算機語言可以解決此問題。
題解:
#include<iostream>
#include<math.h>
using namespace std;
int a[9] = {0};
int count = 0;
bool canPlace(int step, int pos) {
for(int i = 1; i < step; i++) {
if(a[i] == pos || abs(a[i] - pos) == abs(step-i))
return false;
}
return true;
}
void dfs(int step) {
if(step == 9) {
for (int i = 1; i <= 8; i++)
printf("%d ", a[i]);
printf("\n");
count++;
return;
}
for(int i = 1; i <= 8; i++) {
if(canPlace(step, i)) {
a[step] = i;
dfs(step+1);
a[step] = 0;
}
}
}
int main() {
dfs(1);
printf("%d", count);
}
解析:
數組a記錄棋子擺放位置,例如a[3] = 5
表示在第三的第五格放了棋子,任意兩個皇后都同一斜線上,意味着(a[step]-a[i])/(step-i) 的絕對值不能是1
,同一列好理解,a[step] != a[i],同一行不用考慮,因爲我們一行只放一個棋子。