gpt4 book ai didi

c++ - 为什么我的递归函数中的循环是无限的?

转载 作者:行者123 更新时间:2023-11-28 06:46:02 26 4
gpt4 key购买 nike

<分区>

我有以下函数递归检查数独游戏中的每个方 block 以使其合法,并且在运行时我一直遇到段错误,所以我在各处进行 cout 检查以查看它在哪里损坏。不知何故,它停留在循环中并继续一遍又一遍地调用 addSquare 函数,永远不会结束。我如何让它停止?

bool DoTheWork::addSquare(int& depth)
{
depth++;
cout << depth << endl;
if(board.checkZeroes()==false){ //if the game is won, return true
cout << "ifstatement1" << endl;
return true;
}
else {
for(int i = 0; i < 10; i++) {
cout << "loop1" << endl;
for(int j = 0; j < 10; j++) {
cout << "loop2" << endl;
if(this->board.getSquare(i,j)==0) { //go through each
cout << "ifstatement2" << endl;
for(int k = 1; k < 10; k++) {
cout << "loop3" << endl;
//try each number in that square for legality
board.setSquare(i,j,k);
//set that square to the number you are currently on
if(board.isLegal()==false) {
cout << "ifstatement3" << endl;
board.unsetSquare(i,j);
}
//if the board is not legal for that number, unset that square
if(addSquare(depth)==true) {
cout << "ifstatement4" << endl;
return true;
}
//recursive function, if method is true then it will return true
board.unsetSquare(i,j);
}
}
}
}
}
return false;
} // bool DoTheWork::addSquare(int& depth)

在终端中运行时,它会打印以下内容:循环 1循环 2if语句2循环3if语句3130964循环1...并向前直到它说“段错误(核心转储)”

“ifstatement3”后面的数字每增加一次深度就加1。

包括下面的 checkZeroes 函数:

bool Board::checkZeroes()
{
bool zeroPresent = false;
//assume there are no zeroes, easier for coding
for(int i=0; i<9; i++) {
for(int j=0; j<9; j++) {
if(theBoard[i][j] == 0){
//go through each value of theBoard, if any are 0 return true
zeroPresent = true;
}
}
}
return zeroPresent;
} // int Board::checkZeroes()

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com