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 visited, 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?
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<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] < 600 && currentPosition[0] >= 0 &&
currentPosition[1] < 600 && currentPosition[1] >= 0 &&
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<visited.length; i++)
{
if (position[0] == visited[i][0] && position[1] == visited[i][1])
{
return true;
}
}
return false;
}
Thank you.