【发布时间】:2020-10-06 23:22:56
【问题描述】:
8皇后谜题是一个问题,在棋盘的每一列中放置8个棋后,这样两个皇后就不会相互威胁;因此,一个解决方案要求没有两个皇后共享同一行或对角线。我被分配使用一维数组解决 8 个皇后问题并使用蛮力。我知道这是非常低效的,但这是任务,我们已经在之前的任务中使用回溯解决了它。我想出了以下代码,但它不打印任何内容。不知道问题是什么,但我猜我的 ok() 函数,如果它是一个合法的解决方案,它应该返回 true,可能没有正确设置来检查?
#include <cmath>
#include <iostream>
using namespace std;
bool ok(int b[]){
for(int i=0; i<8; i++){
for(int c=0; c<8; c++){
//checks same row, up diagonal, down diagonal for other queens
if(b[i]==b[c]||(c-i)==abs(b[c]-b[i])) return false;
}
}
return true;//if none of these returned false, then the board is ok and we return true
};//end of ok
void print(int b[], int z){//this method prints out the double array
cout<<"Solution: " <<z<<endl;
for(int j =0;j<8;j++){//loop for row
cout<<b[j];
cout<<endl;
}//end of loop for row
cout<<"Done!"<<endl;
};//end of print
int main()
{
int board[8];
int count = 0;
for(int i0 =0; i0 <8; i0 ++)
for(int i1 =0; i1 <8; i1 ++)
for(int i2 =0; i2 <8; i2 ++)
for(int i3 =0; i3 <8; i3 ++)
for(int i4 =0; i4 <8; i4 ++)
for(int i5 =0; i5 <8; i5 ++)
for(int i6 =0; i6 <8; i6 ++)
for(int i7 =0; i7 <8; i7 ++){
board[0]=i0;
board[1]=i1;
board[2]=i2;
board[3]=i3;
board[4]=i4;
board[5]=i5;
board[6]=i6;
board[7]=i7;
//used the indices of the loops to set a configuration in array board...
// if this configuration is conflict-free, print the count and the board
if(ok(board)){
print(board, ++count);//prints board if it is ok
}//end if(ok(board)
//clear/reset the board
board[0]=0;
board[1]=0;
board[2]=0;
board[3]=0;
board[4]=0;
board[5]=0;
board[6]=0;
board[7]=0;
}
return 0;
}
【问题讨论】:
-
您是否单独测试了您的
print功能?它工作正常吗?您是否分别验证了您的ok功能?它工作正常吗? -
为您的
ok函数编写一个测试,以确保它首先正常工作。 -
在 C++ 中将数组传递给函数有点冒险,尽管你知道它们的长度都是 8,这避免了它可能导致的许多问题。在任何情况下,您的
ok函数看起来总是会返回false(它检查的第一件事会发生什么,i = c = 0?)所以你肯定想仔细检查它的逻辑。
标签: c++ arrays for-loop chess brute-force