gpt4 book ai didi

c++ - 如何用蛮力解决 8 皇后一维数组?

转载 作者:行者123 更新时间:2023-11-28 07:44:30 26 4
gpt4 key购买 nike

我的任务是修改 8 Queens 程序以使用一维数组并使用蛮力(已经进行了回溯)。我想出了以下代码:

#include <cmath>
#include <iostream>
using namespace std;

bool ok(int board[8]){

for(int j = 0; j <= 7; j++){ //check for repeating digits
cout << "ok loop 1"<<endl;
for (int k = 0; k <= 7; k++)
{
cout << "ok loop 2"<<endl;
if (board[k] = board[j]){ return false; }
}
}

for(int c = 7; c >= 0; c--){ //check if position is safe
cout << "ok loop 3"<<endl;
//int r = 0;

for(int i = 1; i <= c; i++){
cout << "ok loop 4"<<endl;
if(board[c-i] == c)
return false;
else if ((board[c]-i)>0 && board[c-i]-i == 1)

return false;
else if ((board[c]+i)<=7 && board[c-i]+i == 1)
return false;
} // for loop

} // for loop
return true;
} // ok




void print(int board[8], int c){
cout << "Solution " << c << ": " << endl;
for(int i = 0; i < 8; i++){
{
cout << board[i] <<" ";
}
}

cout << endl;
}




int main ()
{

int b[8]={0}; //initialize the array
int count = 0;

for(b[0]=0; b[0]<8; b[0]++)
for(b[1]=0; b[1]<8; b[1]++)
for(b[2]=0; b[2]<8; b[2]++)
for(b[3]=0 ; b[3]<8; b[3]++)
for(b[4]=0; b[4]<8; b[4]++)
for(b[5]=0; b[5]<8; b[5]++)
for(b[6]=0; b[6]<8; b[6]++)
for(b[7]=0; b[7]<8; b[7]++)
if(ok(b))
{
count++;
print(b, count);
}
system("PAUSE");
return 0;
}

它一直在循环,我不确定为什么。有人介意帮助我吗?

最佳答案

有几点可以改进:

  • 如果您将对八个字符的常量数组的引用传递给 ok(),而不仅仅是指向非常量整数的指针,编译器可能会告诉您其中一个问题。
  • 女王可以有多少个不同的位置?我会说 64,虽然你的代码建议八。我将从记录整个代码中变量和常量的实际含义开始,因为您自己似乎对此感到困惑。
  • 您检查 board[x] 是否为 board[y],但 x 和 y 相等,并据此声称存在重复数字。
  • 你在不同的皇后之间发挥了重要作用。换句话说,您的程序将找到皇后如何放置在相同的八个位置上的所有排列。这不是不正确的,但效率低下。如果您固定职位数量,那将产生显着差异。

关于c++ - 如何用蛮力解决 8 皇后一维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15163016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com