骑士 java_在递归骑士之旅中正确声明变量(Java作业)
我在學年的最后一個項目(我作為CS學生的第一年)的代碼中找不到錯誤.在執行騎士巡回賽問題時,我一直堅持遞歸.這是有問題的文件:
https://github.com/sheagunther/tsp161knightstour/blob/master/KnightsTourRecursiveSearch.java
具體來說,我的問題是這部分代碼(從第265行開始):
else{
for(int i = 0; i < numberOfPossibleNextMoves; i++){
Cell nextCellToMoveTo = candidateNextMoves.get(i);
int currentRowStorage = currentRow;
int currentColumnStorage = currentColumn;
currentRow = nextCellToMoveTo.row;
currentColumn = nextCellToMoveTo.column;
listOfMoves.add(nextCellToMoveTo);
chessBoard[currentRow][currentColumn] = 1;
currentMoveNumber++;
boolean tourFound = findTour();
if(tourFound){
return true;
}
else{ // Undo the last move just made
backtrackCount++;
chessBoard[currentRow][currentColumn] = -1;
currentRow = currentRowStorage;
currentColumn = currentColumnStorage;
listOfMoves.remove(nextCellToMoveTo);
currentMoveNumber--;
}
}
return false;
這是findTour()的結尾.這是程序的一部分,用于測試當前正方形(也稱為單元格)的所有可能移動,如果可以從新移動到正方形完成巡回,則返回true.如果游覽不能從廣場完成,它會進入其他地方{并撤消移動.這就是我認為的問題所在.
現在,如上面的代碼設置,程序陷入無限遞歸循環.
記下else {聲明的這一部分:
chessBoard[currentRow][currentColumn] = -1;
currentRow = currentRowStorage;
currentColumn = currentColumnStorage;
這部分代碼將chessBoard中的方塊更改為-1,這意味著它是未訪問的(1 =已訪問).如上所述,新移動的currentRow和currentColumn用于將方塊設置為未訪問的.然后使用currentRowStorage和currentColumnStorage將這些值重置為先前的跳轉值.
如果我將代碼更改為
currentRow = currentRowStorage;
currentColumn = currentColumnStorage;
chessBoard[currentRow][currentColumn] = -1;
它成功地找到了一個不正確的巡回演出,其中最后1/3左右的動作只是在幾個方格之間來回跳躍.這是預期的,因為它沒有正確處理重置過程.
我懷疑我的問題是由于我在宣布變量的地方.這是我的第一個復雜的遞歸問題,我不確定我是否正確處理currentRow / Column和currentRow / ColumnStorage之間的切換.我應該在當地或多或少地宣布它們嗎?
以下是要求的相關部分:
If the tour is not completed, then findTour determines the (possibly
empty) list of vacant cells that are reachable from the knight’s
current cell, and stores this list in a locally declared list
variable, candidateNextMoves. It is critical that this list variable
be declared local to the method. If this list is empty, then there is
no way to extend the current partial tour, so findTour should return
false. If the list is not empty, then findTour tries extending the
tour by each move on the list as follows. It iterates over the list,
and for each cell of the list it makes the next move to that cell,
updating all of L (the list of moves in the tour), B (the 2D array of
the state of the board (visited, not visted)), currRow, and currCol to
reflect this move. It then recursively calls itself, assigning the
result of the call to a locally declared boolean variable, which you
might name “success”. If success is assigned true, findTour returns
true. If success is false, findTour undoes the move it just made, or
“backtracks”, and tries the next move of candidateNextMoves. You will
maintain a static int variable, backtrackCount, which is initialized
to 0, and incremented for each undo of a move.
一個注意事項 – 我調用了我的布爾值’tourFound’而不是’success’.
總結
以上是生活随笔為你收集整理的骑士 java_在递归骑士之旅中正确声明变量(Java作业)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA报错是一层一层的吗_Java异常
- 下一篇: java lock 对象_Java并发编