A JavaScript program that finds the shortest path for a knight to travel between any two squares on a standard 8x8 chessboard, using Breadth-First Search (BFS).
Given a starting square and an ending square, the program calculates the minimum number of knight moves required to get from one to the other, and prints out the exact sequence of squares visited along the way.
-
Board Setup — Generates all 64 coordinates
[i, j]fori, jin0..7, representing every square on the board. -
Adjacency List — For every square, precomputes all valid knight moves (up to 8 possible L-shaped moves) and stores them in a
Map, keyed by a stringified coordinate (e.g."3,4"). This avoids recalculating moves during the search. -
Move Validation —
isValid(i, j)checks that a coordinate stays within the bounds of the board (0–7 on both axes). -
Move Generation —
getMoves([i, j])returns every legal knight move from a given square, filtered throughisValid. -
Pathfinding —
knightMoves(start, end)performs a BFS:- Starts a queue with a path containing only the
startsquare. - Repeatedly dequeues the current path, checks if its last square matches
end. - If not, expands the path by one move into each unvisited neighboring square and re-queues it.
- Because BFS explores moves in order of path length, the first path that reaches
endis guaranteed to be the shortest one. - Logs the number of moves and the full path to the console.
- Starts a queue with a path containing only the
knightMoves([0, 0], [7, 7]);This will print something like:
=> You made it in 6 moves! Here's your path:
[0,0]
[2,1]
[4,2]
[6,3]
[7,5]
[5,6]
[7,7]
- BFS (Breadth-First Search): Guarantees the shortest path in an unweighted graph (here, the "graph" is the board, and edges are legal knight moves).
- Adjacency List: Precomputed map of square → reachable squares, built once and reused for every search.
- Visited Set: Prevents revisiting squares and infinite loops during traversal.