I am currently programming a recursive algorithm to solve a game of Peg Solitaire.
The algorithm needs to use the "backtracking" approach to solve the board. I think I have managed to get a very close to correct solution. It seems that my code correctly solves the board for all solvable boards. It also seems to correctly determine when a board is not solvable, but only when the number of pegs isn't too high.
My recursive method looks like this:
public static void solve()
{
if(isSolved())
{
long endTime=System.currentTimeMillis();
System.out.println("Solved");
solved=true;
printArr(board);
}
else
{
for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
for (int k=0;k<4;k++)
{
if(makeMove(new int[]{i,j,k}))
{
if(solved!=true)
{
solve();
undoMove();
}
}
}
}
}
}
}
The board is a standard Peg Solitaire board. I am confident that my isSolved() method correctly determines whether the board is solved. My makeMove function takes in a row, column and direction (i, j and k). It finds the peg at those coords and checks if it can move it in the requested direction. If it can, it makes the move, adds the move to an array of moves, and returns true. If not, it returns false.
My undo method pops the last move off of the array and reverts the board to its previous layout (before the popped move was made).
It seems that for random boards with around 25 pegs or more, the program simply won't terminate. It continues processing indefinitely. Solvable boards and various unsolvable boards with less pegs seem to consistently terminate within 10 seconds with the correct result.
Any Ideas?