【发布时间】: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