【发布时间】:2014-07-08 18:31:10
【问题描述】:
我正在尝试找出在棋盘上设置 5 个皇后而不让它们互相攻击的可能方法的数量。我已经成功找到了第一组。问题是我如何才能找到 5 个皇后的下一组位置。我的程序中的程序是这样的:
- 根据棋盘上的当前皇后生成一个包含不允许位置的向量
- 遍历板上的所有位置
- 检查当前位置是否是板上不允许的位置之一
- 如果不是,则返回位置,将其添加到棋盘上的皇后向量中,然后重新开始该过程
继续直到没有更多位置可用,即所有剩余位置都不允许
#include <iostream>
#include <vector>
using namespace std;
const int BSIZE = 8;
char chessBoard[BSIZE][BSIZE];
struct qPos
{
qPos() : h(0), v(0), found(true) {}
int h; //horizontal pos
int v; //vertical pos
bool found; //if position is available
};
qPos findNextQPos(vector<qPos> Qs);
void fillBoard(vector<qPos> Qs);
void print();
vector<qPos> generateDisallowed(vector<qPos> Qs);
bool isDisallowed(qPos nextPos, vector<qPos> disallowedPos);
int main(int argc, char **argv){
vector<qPos> QsOnBoard; //Position of all the queens on board
qPos nextQ; //next possible position
while (nextQ.found)
{
nextQ = findNextQPos(QsOnBoard);
if (nextQ.found)
{
QsOnBoard.push_back(nextQ); //If the nextQ is available i.e. not disallowed, add it to the queens vector
}
}
fillBoard(QsOnBoard); //Fill the board with queens positions
print(); // print the board
return 0;
}
qPos findNextQPos(vector<qPos> Qs) {
// Generate disallowed positions based on all the queens on board
vector <qPos> disallowedPos = generateDisallowed(Qs);
qPos nextQ;
for (size_t i = 0; i < BSIZE; i++)
{
for (size_t j = 0; j < BSIZE; j++)
{
nextQ.h = i;
nextQ.v = j;
if (!isDisallowed(nextQ, disallowedPos)) { //Check if next possible position is a disallowed position
//cout << "Next available:\n" << nextQ.h << ", " << nextQ.v << endl;
return nextQ; // if it is avaible return the position, break the loop
}
}
}
nextQ.found = false; // No available position is found to return, found is set to false, return the position
return nextQ;
}
我拥有其他功能(例如生成禁止和 isDisallowed 等)的其余源代码位于 this pastebin。我认为它与问题无关,这里的代码不应该太长。
第一组的结果如下所示: 那么我应该如何继续才能找到所有解决方案集?这就是我卡住的地方。
【问题讨论】:
-
您是否需要使用代码,或者组合解决方案就足够了?
-
@abiessu 我更喜欢使用代码。使用组合解决方案,我什至不需要走到这一步,对吧?我想可以根据棋盘的大小和皇后的数量来计算。
-
为什么我会否决这个问题?谁能给我解释一下?
-
不确定否决票,您似乎自己做了一些工作以尝试解决方案,并且您似乎试图自己理解问题空间。我建议使用组合路线,因为通过每个解决方案几乎肯定会产生许多重复的皇后阵型,包括在棋盘空间中的旋转和翻转和平移。
-
@abiessu 是的,我知道旋转和翻转会有很多解决方案,但我实际上正在寻找独特的解决方案。但是出于好奇,您能告诉我组合解决方案吗?谢谢