私は現在、再帰的なバックトラックの美しいトピックを研究しています。迷路から最短経路を見つける、またはn-queens問題など、古典的な例をすでに試しました。しかし、私が今取り組んでいる問題は本当に私を混乱させます:実際、私は単純なジグソーパズルを解くのは簡単な練習かもしれないと思いました:私は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で動作するように上記のアルゴリズムを最適化することは可能ですか?私は何が間違っているのですか?それとも私は完全に間違ったアプローチを取っていますか?
よろしくお願いします。