Skip to content
Advertisement

Can someone help me with this knight’s tour code?

The code seems fine to me, but the output is too short and the answer is no when it should be yes (starting at a,0, the knight should be able to tour the entire board)

By the way, the reason my positionsVisted array is [9][9] is because I wanted the values to be 1-8, to match the output.

JavaScript

This is the output of the program:

JavaScript

Advertisement

Answer

Except problem with “all is visited” check I see at least one more problem, which is in class fields. When algorithm passes one branch of recursion, it marks some squares as visited, and since this information is class field, when it fails current branch and starts another, it sees all invalid information from previous attempts.

What if you try to pass positionsVisited, positionX and positionY as method arguments and remove it from class fields, so each method call will have it’s own actual copy?


Final version

JavaScript

Here is the working variation with 6×6 board. With 8×8 board calculations take too much time on my machine. Maybe it can be faster if you randomize move selection.

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