This is a relatively simple algorithmic exercise. The following general approach works for any chess piece:
- Create a local variable - a stack of chess squares. (If the programming language of your choice doesn't provide a stack data structure implementation in its standard library, a double-ended queue (deque) or a list may be used for the stack.) Let's call this variable chessSquaresStack.
- Create a local variable - an 8x8 2D array of integers representing the shortest distance that a given chess piece placed on a given square needs to get to other squares - and initialise all elements of this 2D array with "infinity" - something like the maximum value for an integer. Let's call this variable minimumDistances.
- Write 0 to the square where your examined piece (e.g., a given knight) stands. If your knight is on a3, which is (0 , 2) in zero-based coordinates, it could look like: currentSquare = (0 , 2); minimumDistances[currentSquare] = 0 Then push this square onto the top of the stack; e.g., chessSquaresStack.push(currentSquare)
- While chessSquaresStack is not empty, do:
- Pop the square from the top of the stack; e.g., currentSquare = chessSquaresStack.pop()
- Figure out the "target squares" - the squares that the examined piece can get to from currentSquare in one move. You may want to disregard squares that are occupied by your other pieces. Loop over these squares, storing them in a variable - let's call this variable targetSquare.
- When looping over these target squares, check if minimumDistances[targetSquare] < "infinity". If it is less than "infinity", we may ignore that square because we have previously computed the minimum distance for it. Otherwise, we compute the new distance: minimumDistances[targetSquare] = minimumDistances[currentSquare] + 1 Then push this target square onto the stack - chessSquaresStack.push(targetSquare) - and continue looping over the rest of the target squares.
When chessSquaresStack is empty, the minimumDistances array will contain a single value of 0 (the square where the examined piece stands at the beginning), then a few values of 1 (the squares that the examined piece can get to in 1 move), a few values of 2 (in 2 moves) etc., and a few values of "infinity" (the squares that the examined piece can never get to - because they are occupied by your other pieces).
I'm trying to build a utility tool pack for blindfold chess and one of the tools involves calculating the minimum number of moves to get from one square to another with any piece. The pawn, bishop, queen, and rook are relatively simple (mathematically resolvable), but I don't particularly understand how to go about doing this with the knight. Someone has already suggested a solution utilizing some graph theory but is there, by chance, a simpler way to do this?