我正在爲Java 9x9網格編程一個數獨求解器。Java中的數獨求解器,使用回溯和遞歸
我有方法:
打印網格
與給定的值初始化爲板衝突
測試(如果相同數量的處於同一行或3×3子格)
一種方法來放置數字,一個接一個,這需要最多的工作。
我細講與方法之前,請記住,我不得不用遞歸來解決它,以及(在這裏觀看小程序作爲例子http://www.heimetli.ch/ffh/simplifiedsudoku.html)回溯
另外,我我解決這個數獨的垂直向下運動,從左上角開始,通過第一列,然後通過第二列等
到目前爲止,我有以下幾點:
public boolean placeNumber(int column){
if (column == SUDOKU_SIZE){ // we have went through all the columns, game is over
return true;
}
else
{
int row=0; //takes you to the top of the row each time
while (row < SUDOKU_SIZE) loops through the column downwards, one by one
{
if (puzzle[row][column]==0){ //skips any entries already in there (the given values)
puzzle[row][column]=1; //starts with one
while(conflictsTest(row,column)){ //conflictsTest is the method I wrote, which checks if the given parameters are in conflict with another number
puzzle[row][column] += 1;
}
//BACK TRACKING
placeNumber(column); //recursive call
}
else{
row++; // row already has a number given, so skip it
}
}
column++; // move on to second column
placeNumber(column);
}
return false; // no solutions to this puzzle
}
在哪裏我標記爲BACKTRACKING是我相信我的代碼的其餘部分需要去的地方。
我想到了沿着線的東西:
- 如果該值爲10,設定值回零,回去一排,並通過1
增加該值這回溯「戰略」並不完全有幾個原因的工作:
如果什麼上一行,是一個給定值(又名我不應該增加它或觸摸它,但取而代之的是,回到我放在那裏的最後一個值)
如果前一個值是9,那麼該怎麼辦?如果我遞增了1,現在我們就是10,這是行不通的。
有人能幫我嗎?
+1因爲想學習,而不僅僅是想餵食代碼。 – qJake 2012-02-22 23:08:41
謝謝你spikeX。 – 2012-02-22 23:15:13
從我出於同樣的原因+1。但你知道嗎?我敢打賭,儘管如此,仍然會有代碼。有些人無法抗拒。 – Ingo 2012-02-22 23:30:09