【问题标题】:How can I debug my infinite 8-queens program?如何调试我的无限 8-queens 程序?
【发布时间】:2020-03-30 20:55:28
【问题描述】:

我从使用 go-to 语句的早期版本翻译了该程序,但在某个地方我的逻辑变得混乱,因为它打印了一个无限循环的板,其中唯一的一块是第 0 行第 0 列中的皇后。

我怎样才能找到错误?

bool rowCheck(int board[], int column);
bool diagonalCheck(int board[], int column);
void print (int board[]);

int main(){
    int queens[8];
    int col = 0;
    queens[0] = 0;

    while(col > -1){
        //if current column moves beyond 8th column, print solution and
        if(col == 8){
            print(queens);                          
            col--;  
        }
        //if current row moves beyond the 8th row, resets row to -1 and moves back to previous column;                                                                              
        if(queens[col] == 8){                       
            queens[col] = -1;                       
            col--;                                  
        }
        //if the current board checks true for all columns prior, moves to next column
        else if( rowCheck(queens, col) && diagonalCheck(queens, col) ){
            col++;
        }
        //moves queen to the next row of current column
        else{
            queens[col]++;
        }
    }
    return 0; 
}
//checks previous rows for an adjacent queen
bool rowCheck(int board[] , int column){
    for(int i = 0; i < column; i++){
        if(board[i] == board[column])
            return false;
    }
    return true;
}
//checks previous rows for queens diagonally
bool diagonalCheck(int board[], int column){
    for(int i = 0; i < column; i++){
        if((column - i) == abs(board[column] - board[i]))
            return false;
    }
    return true; 
}
//print
void print(int board[]){
    static int solution = 0; 
    solution++;
    cout << "Solution " << solution << endl;
    for(int row = 0; row < 8; row++){
        for(int column = 0; column < 8; column++)   
            if(board[column] == row)
                cout << "1 ";
            else
                cout << "0 ";

        cout << endl;
    }
    cout << endl;
}

【问题讨论】:

  • 在调试器中逐步完成;应该很容易弄清楚。提示:rowCheck 有问题,你用rowCheck(queens, 0) 调用它。
  • 提示:添加一些诊断打印语句。这将有助于显示运行时的行为。您可能还想添加一个深度计——一个指示递归深度的变量。

标签: c++ debugging logic n-queens


【解决方案1】:

您忘记初始化 queens 数组。它包含除了第一个元素之外的垃圾值,它被正确初始化为 0。因此,您的皇后位于棋盘之外(很可能),rowCheckdiagonalCheck 函数无法找到冲突的皇后。你应该初始化整个数组。

【讨论】:

    猜你喜欢
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2022-01-05
    • 2011-01-06
    相关资源
    最近更新 更多