I've been doing Knights Travails project, and I just can't come up with a solution like I want: (should show the shortest possible way to get from one square to another by outputting all squares the knight will stop on along the way), I can do that it will execute the lenght of the path, but it's not what I want.
function knightMoves(start, end) {
const directions = [[1, 2], [1, -2], [-1, 2], [-1, -2], [2, 1], [2, -1], [-2, 1], [-2, -1]];
const visited = new Set();
const queue = [start];
const path = [start];
while(queue.length) {
const square = queue.shift();
if (square[0] == end[0] && square[1] == end[1]) return path;
for (let d in directions) {
const possibleX = square[0] + directions[d][0];
const possibleY = square[1] + directions[d][1];
if (!visited.has(directions[d] && possibleX >= 0 && possibleX <= 8 && possibleY >= 0 && possibleY <= 8)) {
visited.add(directions[d]);
queue.push(directions[d]);
}
}
}
return path;
}
console.log(knightMoves([0,0],[1,2])); // [[0,0],[1,2]]
// knightMoves([0,0],[3,3]) == [[0,0],[1,2],[3,3]]
// knightMoves([3,3],[0,0]) == [[3,3],[1,2],[0,0]]