【发布时间】:2015-07-02 10:10:33
【问题描述】:
我使用的是 C++,但我的问题更多是关于算法而不是实现。
问题如下:
编写一个程序,输入两个整数 n 和 k,其中 n>=k。你的程序应该计算出 k 个象可以放在 nXn 棋盘上的不同方式的数量。
我的基本想法是将每个主教表示为具有 X 值和 Y 值的结构。然后我将主教放在板上以获得配置。
我编写了一个名为 moveToNextPlace 的方法,它允许我将主教移动到下一个可用位置。我返回一个字符串来帮助调试。
struct bishop {
int y=0;
int x=0;
string moveToNextPlace (int n){
if (y<n-1) {y++; return "move to next y value";}
else if (x<n-1) {x++; return "move to next x value";}
else {reset(); return "reset";};
}
void setValuesLike (bishop b){
y=b.y;
x=b.x;
}
void reset (){
y=0;
x=0;
}
bool clashesWith (bishop b){
if (b.x==x && b.y==y){
return true;
}
if ( b.y-y == b.x-x ) return true; //if their slope is 1
return false;
}
};
然后我通过使用我想要的设置调用 findSolutions 将板设置为初始配置。
int findSolutions (int k, int n){ //k bishops on n*n board
bishop *b = new bishop [k];
for (int i=0; i<k; i++){
findAspot (b, n, i);
}
}
bool check (int num, bishop b[]){
for (int i=0 ; i<num; i++){
if (b[i].clashesWith (b[num])) return false;
}
return true;
}
void findAspot (bishop b[], int n, int num){ //n=boardsize
while (1){
if (check(num, b)){return;}
if (b[num].moveToNextPlace(n) == "reset") break;
}
b[num-1].moveToNextPlace(n);
findAspot (b, n, num-1);
b[num].setValuesLike ( b[num-1] );
findAspot (b, n, num);
}
然后我想继续回溯,直到我有一个总数的解决方案,但我被困在如何找到下一个解决方案。
我想我可以编写一个 findNextSolution,它在 findSolutions 函数结束时一直被调用,直到它到达一个循环。但我不知道用什么算法来寻找下一个解决方案。
【问题讨论】:
-
几乎没有。比较 programmers.stackexchange.com/help/on-topic 和 stackoverflow.com/help/on-topic。一个特别提到算法,另一个则称任何与实现相关的题外话。程序员适用于一般软件方法和过程的东西。 OP 是主题。
-
@Yigal - 你的意思是“放置在 (n,n) 棋盘上,这样没有人会按照通常的国际象棋规则检查任何其他人”,也许?
-
@Badzen 我会这样认为,因为如果你可以将它们放在任何地方,答案就很容易了。
-
@YigalSaperstein 你认为每行/列最多只能存在 1 个主教吗?
-
我回答的问题让您满意吗?
标签: c++ algorithm search chess n-queens