A JavaScript implementation of the Knight's Travails problem from The Odin Project. Given any two squares on a standard 8×8 chessboard, the program finds and prints the shortest possible path a knight can take to get from one to the other.
A chess knight moves in an "L" shape — two squares in one direction and one square perpendicular. The key insight of this project is that the chessboard can be modeled as an implicit graph, where:
- Each square
[x, y]is a vertex - Each valid knight move is an edge to a neighbouring vertex
Breadth-First Search (BFS) is used to traverse this graph, which guarantees the shortest path is always found.
- Node.js installed, or any modern browser console
- Clone or download the repository
- Open a terminal in the project folder
- Run:
node knightMoves.jsknightMoves(start, end)| Parameter | Type | Description |
|---|---|---|
start |
[x, y] |
Starting square, coordinates 0–7 |
end |
[x, y] |
Target square, coordinates 0–7 |
knightMoves([3, 3], [4, 3]);Output:
You made it in 3 moves! Here's your path:
[3,3]
[4,5]
[2,4]
[4,3]
knightMoves([0, 0], [1, 2]);
// You made it in 1 moves! Here's your path:
// [0,0]
// [1,2]
knightMoves([0, 0], [3, 3]);
// You made it in 2 moves! Here's your path:
// [0,0]
// [2,1]
// [3,3]
knightMoves([0, 0], [7, 7]);
// You made it in 6 moves! Here's your path:
// [0,0]
// ...
// [7,7]Note: When multiple shortest paths exist, any one valid path will be returned.
knightMoves.js
│
├── directions # Array of all 8 knight move offsets
├── Queue # Simple queue class used for BFS
├── isValidPosition() # Checks if [x, y] is within the board
├── getValidMoves() # Returns all legal knight moves from a position
├── printPath() # Formats and prints the result
└── knightMoves() # Main BFS function — finds the shortest path
- Enqueue the starting position as a path:
[[start]] - Mark start as visited
- Dequeue the first path; check if its last position is the target
- If yes → print and return the path
- If no → generate all valid knight moves, enqueue unvisited ones as extended paths, mark them visited
- Repeat until the target is found
Since BFS explores all positions reachable in n moves before any reachable in n+1 moves, the first time the target is reached is guaranteed to be via the shortest path.
- Graph theory (implicit graphs, vertices, edges)
- Breadth-First Search (BFS)
- Path tracking via queue entries
- Visited set to prevent revisiting nodes
This project was built as part of The Odin Project curriculum. Free to use and modify.