How to execute all squares the knight will stop on along the way while going from the one position to another?

128 Views Asked by At

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]]
1

There are 1 best solutions below

0
Pedro Del Moral Lopez On

I'm not familiar with the Knight Travails game in question, but if the general gist of the game is "Given a knight on one square, and given a destination square, output the shortest sequence of moves needed to reach that square" then I believe the Uniform Cost Search algorithm (a variant of Dijkstra's shortest path) is your best bet.

The Wiki page provides pseudo-code for how to implement it: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Practical_optimizations_and_infinite_graphs