我有个任务要解决皇后问题。皇后的位置必须是随机的,这就是为什么我有一个洗牌函数。
我们的老师希望我们提示用户输入intn,并从中初始化一个intn数组。然后,我必须调用洗牌函数对数组进行改组和检查,直到列索引中的皇后索引q1 = Q1、q2、qn.不要互相攻击,然后打印第一个解决方案。
例如,{0 2 1 3}对应于位置( 0,0) (行0,0),( 1,2) (第1行,第2列),(2,1) (第2行,第1列)和(3,3) (第3行,第3列)中的4个皇后。注意,在我们的表示中,我们不使用行索引: ithe queen放在ithe行中,它的列索引是qi。要检查序列Qn是否解决了need问题,您需要确保:
时,它们不共享对角。
例:n= 4;
int main(){-displays array before shuffle//0,1,2,3
-shuffle function(array,n) //shuffles each
time a queen is under attack until checkB
== 1(no queens under attack, so until array
findsa solution.
-displays array after finding the first
solution
}
void shuffle(){
//shuffles elements of array to create
random permutations
}
int checkB(int [] b, int n){
do{
//checks if a queen attacks another in the
same column or diagonally
}while(checkfunction == 0);
//checks if the shuffled array has any 皇后区互相攻击,如果没有,就停止循环
}
int displayB(int []b, int n){
//prints the solution b 我的问题是,如果我不知道如何写检查方法,我有一个如何检查列的想法,但对角线我感到困惑,因为我们的老师不希望我们把板转换成一个矩阵,直到我们找到解决方案,然后打印it.ive写的所有其他东西,但没有这个函数,这是我的checkB函数,这是我的checkB函数,任何帮助如何检查它最起码(列)将不胜感激!b[]是被打印的列索引数组。
int checkBoard(int b[], int n){
int result = 1;
int delta R;
int deltaC;
int result =1;
for(int c = 0; c<n; c++){
for(int x = 0; x<n; x++){
deltaR=abs(c - (c+1));
deltaC=abs(b[x]-b[x+1]);
if(deltaR==deltaC){
result =0;
}
}
}
return result;
}输出应该是n的解决方案,但是,正如您所看到的,为了打印无效的数组,我的check函数一定出了问题。这是无效的,因为其中一个皇后是在同一对角线!

发布于 2022-02-22 14:34:53
让我们看看其中的一些问题。
如果对数组进行洗牌的函数编写得很好,则
checkBoard函数即使应该返回任何东西,也不会返回任何东西,因为它的签名和代码中使用它的方式。它还应在发现受到攻击的女王后立即返回,以节省计算时间。关于该函数的实现,我将对嵌套循环进行一些更改:
- for every `i` less than `n`, starting from 0.
- declare two variables `L` and `R` both equal to `b[i]`.
- for every `j` less than `n`, starting from `i + 1` (we don't need to check the previous rows, the queens there already checked their diagonals).
- increment `R` by one and decrement `L` by one (remember to use a `signed` type).
- If `L == b[j]` or `R == b[j]` return `false`, these two queens are on the same diagonal.- return `true`, because no queen is under attack.每次尝试失败时,
https://stackoverflow.com/questions/71221948
复制相似问题