八个皇后二维阵列,带有gotos errror

Eight Queens 2-dimensional array with gotos errror

本文关键字:阵列 errror 带有 二维 gotos 八个      更新时间:2023-10-16

我正在处理带有二维数组的八个皇后问题,当我尝试运行代码时,它给了我细分错误,我似乎无法弄清楚为什么。八个皇后难题是将八个国际象棋皇后放在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;
    }
}

在第三循环中,您检查下对角线,如果一个对角线正方形,则有其他会导致女王放置女王,而您想要它只有在所有对角线正方形都没有占用时才放置。卸下其他,并且可以正常工作(至少在我的机器上可以做)。