我目前正在研究遞歸回溯的美麗主題。 我已經嘗試過尋找經典的例子,例如尋找迷宮中的最短路徑或n皇后問題。但是我現在正在處理的問題真的讓我感到困惑: 其實,我認爲這可能是一個簡單的練習來解決一個簡單的拼圖 - 謎題: 我有一個大小爲n = a * b的板子,很多(n)件。
最後我想把所有的東西都按照一定的順序放在棋盤上,在那裏他們遵守某些限制(比如和他們的鄰居相匹配)。相當容易,我想,我想出了下面的算法:使用遞歸回溯時用盡堆
public board recursiveSolve(Board board, Piece[] pieces, int position){
// base case
if(position == board.getLength())
return board;
else{
// For each possible piece
for(int i = 0; i < pieces.length; i++){
// if the piece is placeable at that position
// place it and search on recursively
if(board.isValid(piece[i], position)){
board.putPiece(pieces[i], position);
// THIS IS THE FISHY PART!!
// Now I need to pass a set of pieces to the function recursively
// that does not contain the current one (pieces[i])
// But I fear my (following) approach is too heap-intensive
Piece[] subPieces = new Piece[pieces.length - 1];
// fill subPieces with all elements from pieces except from the one
// at position i
for (int j = 0; j < subPieces.length; j++) {
if(j >= i)
subPieces[j] = pieces[j+1];
else
subPieces[j] = pieces[j];
}
if(recursiveSolve(board, subPieces, position + 1) != null)
return board;
else
board.removePiece(position);
}
}
// If this is reached, none of the pieces have worked -> go back
return null;
}
嗯,基本上,這個算法做它應該做的 - 但不幸的是它僅適用於「小」板尺寸(N < 100)。 因爲如果我有一塊像10 x 10平方塊和100塊的板子,函數將搜索並搜索,直到由於堆空間不足而導致JVM崩潰時纔會結束。 我甚至嘗試將eclipse的內存大小限制設置爲1.2g,這使得該功能的工作時間更長,但仍然不夠。
所以我的問題是:是否有可能優化上面的算法,使它適用於板尺寸n> 100?我究竟做錯了什麼?還是我採取了完全錯誤的做法?
非常感謝您的幫助提前。
除了語言,這應該適用於n> 100,沒有任何問題。我在代碼中看到一些奇怪的東西,比如你每次構建子目錄,手動去除板子的東西,應該通過回溯自動完成..也許有你的問題? – gbianchi