# Find shortest knight's path between two chessboard squares

My function is a solution to the Knight's Travails problem. It receives start and end point coordinates on a chess board, and must return the shortest path from start to end.

class Node{
constructor(coordinates){
this.value=coordinates
this.possibleMoves=[]
}
}

class Tree{
constructor(startCoordinates){
this.value=startCoordinates
this.possibleMoves=[]

}
}
class Knight{
constructor(){
this.piece="Knight"
this.potentialPaths=null
}
moveKnight(start, end, currentPlay,node,q){
currentPlay=currentPlay||new Tree(start)
node=node||currentPlay
let potentialRoutes= this.possibleMoves(start)
potentialRoutes.forEach(route=>{
let newNode= new Node(route)
node.possibleMoves.push(newNode)
})
q=q||[]
let nodePossibleMoves=node.possibleMoves
nodePossibleMoves.forEach(currentNode=>{
q.push(currentNode)
})
while(q[0].value.toString() !== end.toString()){
let newStart=q.shift()
let newStartPossibleMoves=this.possibleMoves(newStart)
newStartPossibleMoves.forEach(move=>{
q.push(move)
})
this.moveKnight(newStart.value, end, currentPlay, newStart, q)
}
return(currentPlay)
}

possibleMoves(coordinates){
let x=coordinates[0]
let y=coordinates[1]
let potentialMoves=[[x-1,y+2], [x-1,y-2],[x-2,y-1],[x-2,y+1],[x+1,y-2], [x+1,y+2], [x+2,y-1], [x+2,y+1]]
potentialMoves.forEach(move=>{
let x=move[0]
let y= move[1]
if(x<0  || y<0 || x>7 || y>7){
move=null
}
})
return potentialMoves.filter(move=> {
return move[0]>=0 && move[0]<=7 && move[1] >=0 && move[1] <=7
})
}
}

let myKnight= new Knight()
let pathToEnd=(myKnight.moveKnight([0,0], [5,6]))
console.log(pathToEnd)

• How do you get your answer out of this? It looks like pathToEnd ends up being a Tree. I would expect a list of nodes. Commented Sep 9, 2022 at 2:40