Skip to content
Advertisement

java recurison – Need help for solving backtracking Knight’s Tour

I am working on the Knight’s Tour problem. In my program the user can select a number n equal to 3 or higher. The number will determine the table’s size by n*n in a two-dimensional array. Then the knight will start it’s tour based on the starting points given by the user as long as they are higher or equal to 0.

My problem comes when the knight has come to a dead end (as of turn number 12 in the visualization table in the output). I want to somehow track it’s movements so that I can block the dead end, go back a step and try from there. I’ve figured out that I might need a three-dimensional array so that I can save all the turn numbers in each square. But then again I need an ArrayList witch isn’t static. Any suggestions will be appreciated. Here’s my code:

JavaScript

My output for a 4*4 table looks like this:

JavaScript

Advertisement

Answer

When trying different possibilities on BackTracking you need to check them all in every recursion step. In the code you provide in a single step you only try one possibility and then return. Doing this you are not able to explore all the possibilities.

My suggestion is to change the function arguments to accept the current position (x,y) and a boolean array for the positions that have been previously visited. If you need to construct the path of the final valid solution, I also suggest to add the step count (the number of steps you have done) and a int array to store which position has been visited in which step.

Next I provide a solution which is not the most efficient. In fact, you can try to prune the backtracking possibilities to avoid the recurssion explosion (cpu efficiency) and you can try to avoid some copies of the matrixes (memory efficiency).

JavaScript

Try this code with size 5 and start position (0,0).

Notice that:

  • You can enable/disable the debug iteration by commenting the debug call
  • I compacted the way you perform the moves with 2 arrays to avoid replications but for the sake of clarity you can unroll it again.
  • On each recursion step, before going depth, we check if we can perform moves, we mark the next position and proceed. On the way back, we unmark the position, check whether the move reached a successfull step or not and reconstruct the good solution if needed.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement