JSFiddle - React, Tailwind, and code Playground
JavaScript
function isOnBoard(rawPos) {
return rawPos[0] >= 0 && rawPos[0] <= 7
&& rawPos[1] >= 0 && rawPos[1] <= 7;
}
function getNextPositions(pos) {
function toRawPos(strPos) {
return [pos.charCodeAt(0) - 65, pos.charCodeAt(1) - 49];
}
function toStringPos(rawPos) {
return String.fromCharCode(rawPos[0] + 65) + String.fromCharCode(rawPos[1] + 49);
}
const rawPos = toRawPos(pos);
return [
[-2, -1],
[-1, -2],
[1, -2],
[2, -1],
[-1, 2],
[-2, 1],
[1, 2],
[2, 1],
].map(
([deltaX, deltaY]) => [rawPos[0] + deltaX, rawPos[1] + deltaY]
).filter(isOnBoard).map(toStringPos);
}
function findKnightPath(initalPos, targetPos) {
const visited = {};
const paths = [{pos: initalPos, moves: 0, history: [initalPos]}];
while (paths.length) {
const path = paths.shift();
const nextPositions = getNextPositions(path.pos);
for (const nextPos of nextPositions) {
if (nextPos === targetPos) {
return [...path.history, nextPos].join(';');
}
if (!visited[nextPos]) {
paths.push({pos: nextPos, moves: path.moves + 1, history: [...path.history, nextPos]});
visited[nextPos] = true;
}
}
}
return 'nope';
}
document.write(findKnightPath('A1', 'H8'));