Hello I am currently reading at the knight tour problem at Geeksforgeeks https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1 I am testing the code bymyself and when I change the sequence of knight moves at the code
let xMove = [ 2, 1, -1, -2, -2, -1, 1, 2 ];
let yMove = [ 1, 2, 2, 1, -1, -2, -2, -1 ];
to this
let xMove = [1,1,-1,-1,2,2,-2,-2]
let yMove = [2,-2,-2,2,-1,1,-1,1]
and the problem seems doesn't reach to solution. Does this probem relies on the sequence of the knight moves or what is the cause of it? as to my understanding, the recursion will search all possible moves so it should not be difference right?
This is exactly the problem that is also mentioned on Wikipedia:
The order of moves in the implementation you quote from GfG, is a lucky order. With the order that you have tested with, the amount of backtracking is enormous. One can imagine that taking the right moves in the very beginning of the path is crucial. If one of the early moves is wrong, there will be a tremendous amount of backtracking taking place in the deeper nodes of the recursion tree.
There is a heuristic that greatly reduces the number of moves to consider, most of the time only 1: this is Warnsdorff's rule:
In the case of an 8×8 board there is no practical need for breaking ties: the backtracking will resolve wrong choices. But as now the search tree is very narrow, this does not lead to a lot of backtracking, even if we're unlucky.
Here is an implementation in a runnable JavaScript snippet. It intentionally shuffles the list of moves randomly, and prints "backtracking" whenever it needs to backtrack, so that you can experiment on different runs. This will show that this always finds the solution with hardly any backtracking on average: