Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You've got to step back: you haven't even got the backtracking algorithm sorted out and you're already conflating the board you display with the board the algorithm requires. Best bet is to start over, solve the algorithm, and then worry about the display of it all. With that thought, you should solve the algorithm with pseudocode first, and then translate that pseudocode to JavaScript. (Hint: in your code, you never seem to change the current position.)</p> <p>I see the overall process like this:</p> <pre><code>findAllKnightsTours: for every board position set path = empty set board = all false findKnightsTour(currentPosition, path, board) </code></pre> <p>Having the path as a stack is great. Searching through it every time to see if a square has been visited is a pain, so I'd use a separate "board". The board should be a matrix of boolean values (false==not visited, true=visited) although for simplicity I would use a simple array.</p> <pre><code>findKnightsTour(position, path, board): push position onto path set board[position] to true if path.length == 64 print out path else for each of the eight moves next = calculate new position based on move if validPosition(next, board) findKnightsTour(next, path, board) set board[position] to false pop position off path </code></pre> <p>The validPosition routine checks to see if the position is within the board limits and is not currently visited (that is, true).</p> <p>If you look at this routine, you'll see that it adds the current position to the path and to the board, does stuff, and then removes it from the path and board. This is the backtracking part of the algorithm: save some state, try something, and then restore the old state.</p> <p>I leave the JavaScript conversion as an easy exercise for the Reader.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload