Ok, so I have a 3 x 3 jig saw puzzle game that I am writing and I am stuck on the solution method.
public Piece[][] solve(int r, int c) {
if (isSolved())
return board;
board[r][c] = null;
for (Piece p : pieces) {
if (p.equals(prev[r][c])) {
System.out.println("Hello");
break;
}
if (tryInsert(p, r, c)) {
pieces.remove(p);
System.out.println("why");
break;
}
}
if (getPieceAt(r, c) != null)
return solve(nextLoc(r, c).x, nextLoc(r, c).y);
else {
if (prev[prevLoc(r, c).x][prevLoc(r, c).y] == null)
prev[prevLoc(r, c).x][prevLoc(r, c).y] = getPieceAt(
prevLoc(r, c).x, prevLoc(r, c).y);
prev[r][c] = null;
pieces.add(getPieceAt(prevLoc(r, c).x, prevLoc(r, c).y));
return solve(prevLoc(r, c).x, prevLoc(r, c).y);
}
}
I know I haven't provided much info on the puzzle, but my algorithm should work regardless of the specifics. I've tested all helper methods, pieces
is a List
of all the unused Piece
s, tryInsert
attempts to insert the piece in all possible orientations, and if the piece can be inserted, it will be. The idea of prev
is to prevent the program from going thru the same combinations of pieces over and over.
Unfortunately, when I test it, I get a StackOverflowError
. What's wrong?