Program to find out the minimum number of moves for a chess piece to reach every position in Python

In chess, different pieces have unique movement patterns. This program solves the problem of finding the minimum number of moves for a special chess piece to reach every position on an n×n chessboard from the starting position (0, 0).

The special piece moves in an L-shape pattern defined by parameters a and b. From position (x1, y1), it can move to (x2, y2) where:

  • x2 = x1 ± a, y2 = y1 ± b
  • x2 = x1 ± b, y2 = y1 ± a

Algorithm Approach

We use Breadth-First Search (BFS) to find the shortest path from (0, 0) to each target position. BFS guarantees the minimum number of moves since it explores all positions at distance 1 before distance 2, and so on.

Implementation

from collections import defaultdict, deque

def path_search(i, j, n):
    """Find minimum moves from (0,0) to (n-1,n-1) using piece with moves (±i,±j) and (±j,±i)"""
    temp_list = defaultdict(lambda: (-1, -1))
    queue_positional = deque([(0, 0)])
    
    # All possible moves for the piece
    moves = [(i, j), (-i, j), (i, -j), (-i, -j), (j, i), (j, -i), (-j, i), (-j, -i)]
    
    while queue_positional:
        current_element = queue_positional.popleft()
        
        for move in moves:
            x = move[0] + current_element[0]
            y = move[1] + current_element[1]
            
            # Check if position is valid and unvisited
            if 0 <= x < n and 0 <= y < n and temp_list[(x, y)] == (-1, -1):
                temp_list[(x, y)] = current_element
                queue_positional.append((x, y))
                
                # If we reached the target position
                if x == n - 1 and y == n - 1:
                    count_var = 1
                    while temp_list[(x, y)] != (0, 0):
                        count_var += 1
                        x, y = temp_list[(x, y)]
                    return count_var
    
    return -1

def solve(n):
    """Solve for all piece types and print the minimum moves matrix"""
    board = defaultdict(lambda: -1)
    
    # Calculate minimum moves for each piece type (i,j)
    for i in range(1, n):
        for j in range(1, i):
            if board[(i, j)] == -1:
                board[(i, j)] = path_search(i, j, n)
                board[(j, i)] = board[(i, j)]  # Symmetric case
        
        # Special case: when piece moves in straight line
        if (n - 1) % i == 0:
            board[(i, i)] = (n - 1) // i
    
    # Print the results matrix
    for i in range(1, n):
        row = []
        for j in range(1, n):
            row.append(str(board[(i, j)]))
        print(' '.join(row))

# Test with n = 6
solve(6)
5  4  3  2  5
4 -1  2 -1 -1
3  2 -1 -1 -1
2 -1 -1 -1 -1
5 -1 -1 -1  1

How It Works

The algorithm works in two main phases:

  1. BFS Search: For each piece type (i, j), we perform BFS from (0, 0) to find the shortest path to (n-1, n-1)
  2. Path Reconstruction: Once the target is reached, we backtrack through the parent pointers to count the total moves

Key Points

  • Each cell (i, j) in the output represents a different piece type with moves (±i, ±j)
  • -1 indicates the target position is unreachable with that piece type
  • The algorithm uses symmetry to avoid redundant calculations
  • Special diagonal cases are handled separately for efficiency

Conclusion

This program efficiently calculates the minimum moves for various chess piece types using BFS. The approach guarantees optimal solutions and handles unreachable positions gracefully by returning -1.

Updated on: 2026-03-26T00:49:46+05:30

723 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements