use*_*542 2 java stack-overflow recursion sudoku
所以我认为我认为java中的数独求解器的代码非常好,但我需要一些帮助.当我将它嵌入main方法时,它给了我一个堆栈溢出.问题是我的方法不知道如何扭转并修复它的错误.我需要一个布尔标志(一个与下面的代码中使用的标志不同,实际上最好工作)或其他东西让它知道什么时候应该转回来,什么时候它可以再次前进并继续解决游戏.谢谢你提供的所有帮助
public void play(int r, int c){//this method throws the StackOverflowError
if(needAtLoc(r,c).size()==9){
int num=1+generator.nextInt(9);
setCell(r,c,num,this);
if(c<8){
System.out.println(this);///////////////
play(r, c+1);
}
else{
play(r+1, 0);
}
}
else{
if(needAtLoc(r,c).size()==0){//no possible moves THIS IS THE PROBLEM LINE!!!
if(c>0){
play(r, c-1);//play last cell, in column to left
}
else{
if(r==0){
play(r,c);//first square, so must play again (can't go back)
}
else{
play(r-1, 8);/*first cell of row so must go to previous row and
the end column*/
}
}
}
else{//if there are possible moves
int num=needAtLoc(r,c).remove(generator.nextInt(needAtLoc(r,c).size()));
setCell(r,c,num,this);//set the value of the cell
System.out.println(this);//////////////
if(r==8 && c==8){//the end of the cell has been reached so must end recursive call
return;
}
else{
if(c<8){
play(r, c+1);//normal, next cell
}
else{
play(r+1, 0);/*last cell in row so we go to next one
in the first column ("return" button)*/
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*ing 24
我不会为你解决这个问题,而是会就如何解决这个问题提出一些建议.9个小时是充足的.
1)您的代码难以阅读.试着把它分开一点.为变量提供有意义的明确名称(这有助于您和其他人阅读您的代码).您可能犯了一个简单的错误,清洁代码会使这些更容易被发现.尝试将其分解为更小的方法,因为这将使其更具可读性和可维护性.
2)当您进行太多嵌套方法调用并且在递归代码中很常见时,会导致堆栈溢出(通常我相信).因此,请使您的递归清晰.确保您有一个将终止的基本案例.
很抱歉不给你"答案",但由于这听起来像是家庭作业,我认为学习如何自己解决这个问题更有价值.希望看起来很公平.