我遇到了創建隨機數獨網格的問題。我試着修改一個我用來解決這個難題的遞歸模式。謎題本身是一個二維整數數組。這是我(順便說一句,該方法不只是隨機的第一行我有一個想法,以隨機的第一行,然後就決定做全網格):Sudoku遞歸問題(Java)
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))
我不明白數組索引如何去那麼高。誰能幫我嗎?
哇..我忘了添加參數。我非常愚蠢。 – SkylineAddict 2011-01-13 02:51:49