遞迴實現解決8皇后問題
阿新 • • 發佈:2019-01-29
參考 劍指offer 實現的
#include <iostream> #include <string> using namespace std; int Num = 0; void Permutation(int *pInt, int *pBegin) { if (pBegin == pInt + 7) { bool Mark = true; for (int i = 0; i < 8; i++) for (int j = i + 1; j < 8; j++) if (i - j == pInt[i] - pInt[j] || j - i == pInt[i] - pInt[j]) { Mark = false; break; } if (Mark) Num++; } else { for (int *an = pBegin; an <= pInt + 7; an++) { int temp = *an; *an = *pBegin; *pBegin = temp; Permutation(pInt, pBegin + 1); temp = *an; *an = *pBegin; *pBegin = temp; } } } void Permutation(int *pInt) { Permutation(pInt, pInt); cout << Num << endl; } int main() { int ColumnIndex[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; Permutation(ColumnIndex); }