编写一个实验程序采用优先队列式分支限界法求解4皇后问题的一个解 将一个4x4的棋盘用二维数组表示
#include
const int N = 4; int queen[N]; // 存放每行皇后的列号
struct Node { int row; int col; int threat; // 剩余威胁数 Node(int r=0, int c=0, int t=0): row(r), col(c), threat(t) {} bool operator < (const Node& b) const { return threat > b.threat; // 剩余威胁数越小,优先级越高 } };
int calcThreat(int row, int col) { int cnt = 0; for (int i = 0; i < row; i++) { // 检查前面的每一行 if (queen[i] == col) cnt++; // 同列 if (queen[i]+i == col+row) cnt++; // 同一主对角线 if (queen[i]-i == col-row) cnt++; // 同一副对角线 } return cnt; }
bool solve() {
priority_queue
int main() { if (solve()) { cout << "Solution:" << endl; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (j == queen[i]) { cout << "Q "; } else { cout << ". "; } } cout << endl; } } else { cout << "No solution." << endl; } return 0;
原文地址: https://www.cveoy.top/t/topic/d3L0 著作权归作者所有。请勿转载和采集!