8 Queens蛮力问题未打印出结果,C ++

问题描述

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;
}

解决方法

您正在IloArray<IloNumArray>内部的循环中比较每个女王/王后。您可以像这样轻松修复它:

ok()

这正确地给出了92个解决方案。

如果您懒得数数,请运行bool ok(int b[]){ for(int i=0; i<8; i++){ for(int c=i+1; c<8; c++){ // Now c != i :)