我在第25行(随机数)和第29行(其中fillGrid()以递归方式调用自身)遇到了传奇的StackOverflow错误。我想知道为什么会发生这种情况,因为我已经提供了随机数增加1以防它不合法,如果没有数字可行,那么重新开始一切。我不希望得到一个Sudoku生成器算法,因为我可以用Google搜索,我希望得到一个答案,为什么这是错误的。添加一个计数器显示程序在堆栈溢出之前运行了5923次。
import java.util.Random;
class Sudoku{
private Random random = new Random();
private int grid[][] = new int[9][9];
private int rndm, rowLB, rowUB, columnLB, columnUB;
private int count=0;
private void initialise(){
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
grid[i][j]=0;
}
}
}
private void fillGrid(){
initialise();
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
rndm = random.nextInt(9);
insert(rndm, i, j);
if (count==10){
initialise();
fillGrid();
}
}
}
}
private void insert(int number, int row, int column){
if(check(number, row, column)){
grid[row][column]=number;
}else if (count<=9){
count++;
insert((++number)%9, row, column);
}else{
return;
}
}
private boolean check(int number, int row, int column){
for (int i=0; i<9; i++) {
if (grid[i][column] == number || grid[row][i] == number) {
return false;
}
}
findBox(row, column);
for (int i=rowLB; i<rowUB; i++) {
for (int j=columnLB; j<columnUB; j++) {
if (grid[i][j]==number && !(i==row && j==column)){
return false;
}
}
}
return true;
}
private void findBox(int row, int column){
if (0<=row && row<=2){
rowLB=0; rowUB=2;
}else if (3<=row && row<=5){
rowLB=3; rowUB=5;
}else{
rowLB=6; rowUB=8;
}
if (0<=column && column<=2){
columnLB=0; columnUB=2;
}else if (3<=column && column<=5){
columnLB=3; columnUB=5;
}else{
columnLB=6; columnUB=8;
}
}
public static void main(String args[]){
Sudoku ob = new Sudoku();
ob.fillGrid();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(ob.grid[i][j]);
}
System.out.println();
}
}
}