It's a BFS solution.
fucntion getKnightMoves(array)>>returns an array of all possible next moves within the bounds of 0-7fuction isMatched(current, target)>>>compares the current position to the target positionandreturns >> true or false based on whether they are the same
function knightTravails(start, target)
- Checks whether the
targetandstartare the same, if they are then theyreturn>>>>{moves: 0}, path:[]} Qis our Queue instanceQinitialized as ->{pos: start}, path:[start]}whereposis position,pathis the container for all the nodes we traverse.visitedkeeps track of the visitedposwhich contains a set of visitedposas strings (so we can compare them easily)
WHILE (Q is not empty)dequefirstposin thequeueFOR every next move in getKnightMoves(pos)IF next move is not visited-
create a
newPathwhich contains all the current paths, and thenextwe just got. -
IF 'next move' is matching the targetreturn>>>>length of the newPath - 1as total moves andnewPathas all the position needed to get to the target.
-
ELSE just add it to the set of visited nodes & put it in the Queue to explore it's next moves
-
Q = [
{
pos: [i, j],
path: [[i,j], .... [i, j]],
},
...
...
...
]
for next of [[new i, new j], [new i, new j], ....]; // all possible moves
next = [new i, new j];
newPath = [[i, j], .... [new i, new j]];