八皇后二维数组有错误

时间:2017-09-16 22:32:25

标签: c++ arrays

我正在研究带有二维数组的八皇后问题,当我尝试运行代码时,它给了我一个分段错误,我似乎无法找出原因。 八个皇后谜题是在8x8棋盘上放置八个国际象棋皇后的问题,这样就没有两个皇后互相威胁。因此,解决方案要求没有两个皇后共享相同的行,列或对角线。

#include <iostream>
using namespace std;   

void print(int b[][8]);

int main()
{
    int b[8][8]={0},  
      r,
      c=0;
    b[0][0]=1; //putting 1st queen piece on the upper left corner

    /*column section*/
    next_col:
    ++c; //advance column position
    if(c==8) //if solutions for columns0-7 are found then print
        goto print;
    r = -1; //if not, start at the top of the column

    /*row section*/
    next_row:  
    ++r;
    if(r==8)
        goto backtrack;

    for(int i=0; i<c; ++i) 
        if(b[r][i] == 1)
            goto next_row;

    for(int i=1; (r-i)>=0 && (c-i)>=0; ++i)
        if(b[r-i][c-i]==1) //if conflict found in updiagonals
            goto next_row;

    for(int i=1; (r+i)<8 && (c-i)>=0; ++i)
        if(b[r+i][c-i] ==1) //if conflict found in down diagonal try next row
            goto next_row;
        else
            b[r][c]=1; //no conflicts found, so place queen & move to next col
    goto next_col;

    /*backtrack section*/
    backtrack:
    --c; //go back one column
    if(c== -1) // if past first column, all solutions found so terminate prog
        return 0;
     r = 0; //start looking from first row
     while(b[r][c]!=1) // while we haven't found the queen
         ++r; //move to next row of current column
     b[r][c]=0; //remove queen piece
     goto next_row;

     /*print section*/
     print:
     print(b); // print the board
     goto backtrack;
}   

void print(int b[][8])
{
    for(int i=0; i<8; i++)
    {
        for(int j=0; j<8; j++)
            cout << b[i][j] << " ";
        cout << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

在第三个for-loop中,检查向下对角线,如果其中一个对角线方块未被占用,则会有一个其他因素会导致放置一个女王,而你希望它只在所有的情况下被放置对角线方块没人住。删除其他,它工作正常(至少它在我的机器上)。