我在创建随机数独网格时遇到问题。我尝试修改用于解决难题的递归模式。拼图本身是一个二维整数数组。这就是我所拥有的(顺便说一句,该方法不仅随机化第一行。我有一个随机化第一行的想法,然后决定做整个网格):
public boolean randomizeFirstRow(int row, int col){
Random rGen = new Random();
if(row == 9){
return true;
}
else{
boolean res;
for(int ndx = rGen.nextInt() + 1; ndx <= 9;){
//Input values into the boxes
sGrid[row][col] = ndx;
//Then test to see if the value is valid
if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid)){
// grid valid, move to the next cell
if(col + 1 < 9){
res = randomizeFirstRow(row, col+1);
}
else{
res = randomizeFirstRow( row+1, 0);
}
//If the value inputed is valid, restart loop
if(res == true){
return true;
}
}
}
}
//If no value can be put in, set value to 0 to prevent program counting to 9
setGridValue(row, col, 0);
//Return to previous method in stack
return false;
}
这会导致 ArrayIndexOutOfBoundsException 异常高或低(+- 100,000)。我试图看看它在方法中的应用程度,它永远不会超出这条线:
if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid))
我不明白数组索引如何变得如此之高。谁能帮我吗?