我正在实施 nqueens min-conflict 搜索,如所述
Norvig, S., & Peter, J. R. and. (2014). Artificial Intelligence A Modern Approach. In Pearson (Vol. 58, Issue 12).
作者提到,仅此启发式就非常有效:
然而,当我实现它时,我无法在一分钟内解决超过 5000 个问题。虽然作者在 50 次迭代中实现了百万皇后的速度,但我的实现通常会超过 1000 次迭代以实现 5000 皇后。另一个问题 https://stackoverflow.com/questions/27697929/fast-heuristic-algorithm-for-n-queens-n-1000提到了类似的结果。
关于我做错了什么有什么想法吗?是算法问题还是我使用了不应该使用的循环?
update()
顺便说一下,这是主要方法。
list<unsigned> rowsInConflict(const unsigned currentState[]) {
list<unsigned> rowsInConflict; //TODO change to map
for (unsigned row = 0; row < boardSize; row++) {
for (unsigned otherRow = 0; otherRow < boardSize; otherRow++) {
if (isConflict(row, currentState[row], otherRow, currentState[otherRow])) {
rowsInConflict.push_front(row);
debug("row in conflict " + to_string(row));
rowsInConflict.push_front(otherRow);
//return rowsInConflict;
}
}
}
return rowsInConflict;
}
bool update(unsigned currentState[]) {
unsigned randomRow, column;
list<unsigned> conflictRows = rowsInConflict(currentState);
if (conflictRows.empty()) {
return true;
}
list<unsigned>::iterator it = conflictRows.begin();
std::advance(it, rand() % conflictRows.size());
randomRow = (unsigned) *it;
column = getMinConflictColumn(currentState, randomRow);
placeQueen(currentState, randomRow, column);
return false;
}
void solve_nqueen(unsigned size, bool isVerbose) {
unsigned rowSpace[size];
while (!update(rowSpace)) {
if (iterations >= 1000) {
cout << "Random restart." << endl;
intialize(rowSpace);
iterations = 0;
}
iterations++;
}
printBoard(rowSpace);
}
};