簡體   English   中英

如何調試我的無限八皇后程序?

[英]How can I debug my infinite 8-queens program?

我從使用 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;
}

您忘記初始化queens數組。 它包含除第一個元素之外的垃圾值,第一個元素被正確初始化為 0。因此,你的皇后被rowCheck在板外(最有可能),並且rowCheckdiagonalCheck函數無法找到沖突的皇后。 您應該初始化整個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM