Note that there are some explanatory texts on larger screens.

plurals
  1. POSolving Knight's Tour with Backtracking (javascript)
    text
    copied!<p>I am trying to write an algorithm in javascript to solve the Knight's Tour problem using Backtracking, but it doesn't work. Basically, the function is supposed to output an array called <em>visited</em>, which contains the locations of each moves. However, no location is appended to the array, which remains as [[0,0]]. Here is my code. Any clue? </p> <pre><code>var unit = 75; function m1(position) { position[0] += unit; position[1] += 2*unit; return [position[0],position[1]]} function m2(position) { position[0] -= unit; position[1] += 2*unit; return [position[0],position[1]]} function m3(position) { position[0] += 2*unit; position[1] += unit; return [position[0],position[1]]} function m4(position) { position[0] -= 2*unit; position[1] += unit; return [position[0],position[1]]} function m5(position) { position[0] += unit; position[1] -= 2*unit; return [position[0],position[1]]} function m6(position) { position[0] -= unit; position[1] -= 2*unit; return [position[0],position[1]]} function m7(position) { position[0] += 2*unit; position[1] -= unit; return [position[0],position[1]]} function m8(position) { position[0] -= 2*unit; position[1] -= unit; return [position[0],position[1]]} var moves = [m1, m2, m3, m4, m5, m6, m7, m8]; var currentPosition = [0, 0]; var visited = [currentPosition]; function knightour(currentPosition) { var j; if (promising(currentPosition)) { if (visited.length == 64) { return visited; } else { for (j=0; j&lt;moves.length; j++) { context.drawImage(knight, currentPosition[0], currentPosition[1]); alert("NEXT"); visited.push(moves[j](currentPosition)); knightour(currentPosition); } } } } function promising(currentPosition) { if (currentPosition[0] &lt; 600 &amp;&amp; currentPosition[0] &gt;= 0 &amp;&amp; currentPosition[1] &lt; 600 &amp;&amp; currentPosition[1] &gt;= 0 &amp;&amp; isVisited(currentPosition, visited)) { return true; } else { return false; } } function isVisited(position, visited) // visited is an array of size n of array of size 2 ([x,y]) { // currentPosition is an array of size 2 ([x,y]) for (var i=0; i&lt;visited.length; i++) { if (position[0] == visited[i][0] &amp;&amp; position[1] == visited[i][1]) { return true; } } return false; } </code></pre> <p>Thank you.</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