I'm using Java to solve the 8-Puzzle problem using DFS.
this is what I came up with:
public static boolean found = false;
public void solveDepthFirst(EightPuzzle currentState, int lastMove){
if(currentState.goal()){
System.out.println(currentState);
found = true;//to stop DFS when a solution is found (even if not optimal)
return;
}
for(int i=0;i<numMoves;++i){
if(found) return;
EightPuzzle e = currentState.move(i);//0 = up, 1 = down, 2 = left, 3= right
if(!e.equals(currentState) && i != lastMove
&& !visitedNodes.contains(e.toString())){
solveDepthFirst(e, i);
}
if(!visitedNodes.contains(currentState.toString())){
visitedNodes.add(currentState.toString());
}
}
}
!e.equals(currentState) checks if move is possible. (if currentState.move(i) is out of bounds move() returns the same state)
i != lastMove makes sure that if in your last move you moved right you don't move left now (since it doesn't make sens)
visitedNodes is a HashSet of visited Nodes.
This is running out of stack space. When I use -xss10m to increase the stack space from 128k to 10m the algorithm works fine. However I'm sure there are a ton of other optimizations that can be made.
any tips would be greatly appreciated.