gpt4 book ai didi

java - 带回溯的数独算法不返回任何解

转载 作者:行者123 更新时间:2023-12-01 14:39:15 25 4
gpt4 key购买 nike

我对数独算法有点困惑,我使用回溯对其进行编码,并遵循这应该可行的理论步骤,并且我尝试调试它,但是太难了(是的,它解决了一些数字并且确实东西)

我把代码贴出来,希望你能帮帮我,我真的看不出问题出在哪里......

public void backtracking(int row,int col){
if(row > 8){
System.out.println("Solution Found!!");
printSudoku();

}
if (m[row][col] != 0){
next(row, col);
}
else {
for(int i =1; i < n;i++)
if(row(row, i) && col(col, i)) {
m[row][col] =i;
next(row, col);
}
m[row][col] = 0;
}


}

public void next( int row, int col ) {
if( col < 8)
backtracking( row, col + 1 ) ;
else
backtracking( row+ 1, 0 ) ;
}

public boolean region(int x, int y, int numReg) {
x = (x / 3) * 3 ;
y = (y / 3) * 3 ;
for( int r = 0; r < 3; r++ )
for( int c = 0; c < 3; c++ )
if( m[x+r][y+c] == numReg )
return false ;

return true ;
}

public boolean row(int x, int k){
for(int i =0; i < 9; i++)
if(m[x][i] == k)
return false;
return true;
}

public boolean col(int x, int k){
for(int i =0; i < 9; i++)
if(m[i][x] == k)
return false;
return true;
}

我省略了“printSudoku”方法,它只是一个 double ,你知道。

最佳答案

代码看起来几乎是正确的。据我所知,您只是忘记调用区域方法。我看不出变量 n 来自哪里。尝试使用稍微修改的回溯方法:

    public static void backtracking(int row, int col) {
if (row > 8) {
System.out.println("Solution Found!!");
printSudoku();
System.exit(0); //exiting after solution is found
}
if (m[row][col] != 0) {
next(row, col);
} else {
for (int i = 1; i <= 9; i++) //replaced i < n with i<=9
if (row(row, i) && col(col, i) && region(row, col, i)) { //calling region method too
m[row][col] = i;
next(row, col);
}
m[row][col] = 0;
}

}

关于java - 带回溯的数独算法不返回任何解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16152166/

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