Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created March 5, 2020 01:36
Show Gist options
  • Save RP-3/907ef211e8bffcc7e56b59bc1731c7ce to your computer and use it in GitHub Desktop.
Save RP-3/907ef211e8bffcc7e56b59bc1731c7ce to your computer and use it in GitHub Desktop.
// Straight-up BFS. Very slow but accepted...
var minKnightMoves = function(x, y) {
const queue = [[0, 0, 0]]; // x, y, distance
const visited = new Map(); // `x:y`: distance
while(queue.length){
const [X, Y, dist] = queue.shift();
if(visited.has(`${X}:${Y}`)) continue;
visited.set(`${X}:${Y}`, dist);
if(X === x && Y === y) return dist;
[
[X + 2, Y + 1],
[X + 2, Y - 1],
[X - 2, Y + 1],
[X - 2, Y - 1],
[X + 1, Y + 2],
[X + 1, Y - 2],
[X - 1, Y + 2],
[X - 1, Y - 2],
].forEach(([x1, y1]) => {
if(!visited.has(`${x1}:${y1}`)){
queue.push([x1, y1, dist + 1]);
}
});
}
};
// Seriously Optimized after getting some inspiration...
var minKnightMoves = function(x, y) {
x = Math.abs(x); // since the board is symetrical, make everything positive
y = Math.abs(y); // to make life easier for ourselves
const s = [ // if our knight is < 5 squares away, we just cache the answer.
[0, 3, 2, 3, 2], // s[x][y] = the number of moves the knight must make
[3, 2, 1, 2, 3], // to get from s[x][y] to 0,0.
[2, 1, 4, 3, 2],
[3, 2, 3, 2, 3],
[2, 3, 2, 3, 4]
];
let result = 0; // count moves
// while the knight is > 4 squares away, be greedy.
while(x > 4 || y > 4){ // if its further away in the x axis
if(x > y){ // prioritise moving x
if(x > 0) x-=2; // move two squares along the x
else x+=2; // and one along the Y
y = y > 0 ? (y-1) : (y+1);
}else{ // prioritise moving y
if(y > 0) y-=2;
else y+=2;
x = x > 0 ? (x-1) : (x+1);
}
result++;
}
// Woohoo! Our knight is now < 5 squares from the end
return result + s[x][y]; // return the cached answer from this point
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment