Skip to content
Advertisement

Knight tour problem – order of moves affect performance

I was trying to implement a solution for knight tour problem. I faced an interesting issue. I would like to know the reason for the behavior.

This is the code – it works fine.

JavaScript

Now we could run this, starting with knight position as (2, 2) in the matrix

JavaScript

When i tried to run the starting position as (0, 0) , it ran continuously without showing any results. So i thought there could not be any solution for it. But if i change below order slightly, It works fine immediately.

JavaScript

What is really going on? how does this position of moves could affect the performance this much? then in that case, how do we know the correct order of the moves?

Advertisement

Answer

You are doing a brute force search through a very large search space. If you’re unlucky in how you do your search, you can spend a long time with no solution showing up.

The answer is that either you are lucky in your choice of starting place/starting pattern, or else you need to be smarter about recognizing “hopelessly stuck”.

For example every 10,000 times that you backtrack, do a scan of the whole board. If you can find hole that you cannot possibly get back to, then set a flag that causes you to backtrack to the last move that you could have visited it from. Then continue. This lets you skip over a potentially big chunk of useless work and get back to finding one of the many possible tours that are to be found.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement