Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

Knight's Moves

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).

Overview

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.

How It Works

  1. Board Setup — Generates all 64 coordinates [i, j] for i, j in 0..7, representing every square on the board.

  2. 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.

  3. Move Validation — isValid(i, j) checks that a coordinate stays within the bounds of the board (0–7 on both axes).

  4. Move Generation — getMoves([i, j]) returns every legal knight move from a given square, filtered through isValid.

  5. Pathfinding — knightMoves(start, end) performs a BFS:

    • Starts a queue with a path containing only the start square.
    • 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 end is guaranteed to be the shortest one.
    • Logs the number of moves and the full path to the console.

Usage

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]

Key Concepts

  • 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.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages