Skip to content

kodi73/Project-Knights-Travails

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

Knight's Travails

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.

How It Works

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.

Usage

Prerequisites

  • Node.js installed, or any modern browser console

Running the Program

  1. Clone or download the repository
  2. Open a terminal in the project folder
  3. Run:
node knightMoves.js

Function Signature

knightMoves(start, end)
Parameter Type Description
start [x, y] Starting square, coordinates 0–7
end [x, y] Target square, coordinates 0–7

Example

knightMoves([3, 3], [4, 3]);

Output:

You made it in 3 moves! Here's your path:
[3,3]
[4,5]
[2,4]
[4,3]

More Examples

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.

Project Structure

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

Algorithm

  1. Enqueue the starting position as a path: [[start]]
  2. Mark start as visited
  3. Dequeue the first path; check if its last position is the target
  4. If yes → print and return the path
  5. If no → generate all valid knight moves, enqueue unvisited ones as extended paths, mark them visited
  6. 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.

Concepts Covered

  • Graph theory (implicit graphs, vertices, edges)
  • Breadth-First Search (BFS)
  • Path tracking via queue entries
  • Visited set to prevent revisiting nodes

License

This project was built as part of The Odin Project curriculum. Free to use and modify.