Program to find minimum steps to reach target position by a chess knight in Python

Finding the minimum number of moves for a chess knight to reach a target position is a classic problem that can be solved using mathematical optimization. A knight moves in an L-shape: two squares in one direction and one square perpendicular to that direction.

Problem Understanding

Given a knight starting at position (0, 0) on an infinite chessboard, we need to find the minimum steps to reach position (r, c). The knight has 8 possible moves from any position ?

K Knight's 8 Possible Moves

Algorithm Approach

The solution uses mathematical optimization with special cases. We can reduce the problem by using symmetry - if r

def min_knight_moves(r, c):
    # Use symmetry to reduce problem space
    if r < c:
        r, c = c, r
    
    # Special cases with known optimal solutions
    if (r, c) == (1, 0):
        return 3
    if (r, c) == (2, 2):
        return 4
    
    # Mathematical formula for general case
    delta = r - c
    if c > delta:
        return delta - 2 * ((delta - c) // 3)
    else:
        return delta - 2 * ((delta - c) // 4)

# Test the function
r, c = 6, 1
result = min_knight_moves(r, c)
print(f"Minimum moves to reach ({r}, {c}): {result}")
Minimum moves to reach (6, 1): 3

Step-by-Step Example

For reaching position (6, 1), the knight takes 3 moves ?

def show_path_example():
    print("Path from (0,0) to (6,1):")
    print("Move 1: (0,0) ? (2,1)")
    print("Move 2: (2,1) ? (4,0)")  
    print("Move 3: (4,0) ? (6,1)")
    print("Total moves: 3")

show_path_example()
Path from (0,0) to (6,1):
Move 1: (0,0) ? (2,1)
Move 2: (2,1) ? (4,0)
Move 3: (4,0) ? (6,1)
Total moves: 3

Testing Multiple Cases

def test_multiple_positions():
    test_cases = [(1, 1), (2, 2), (3, 3), (6, 1), (0, 0)]
    
    for r, c in test_cases:
        moves = min_knight_moves(r, c)
        print(f"Position ({r}, {c}): {moves} moves")

test_multiple_positions()
Position (1, 1): 2 moves
Position (2, 2): 4 moves
Position (3, 3): 2 moves
Position (6, 1): 3 moves
Position (0, 0): 0 moves

How the Algorithm Works

The algorithm uses these key insights:

  • Symmetry: We can swap coordinates to reduce the search space
  • Special Cases: Positions (1,0) and (2,2) have known optimal solutions
  • Mathematical Formula: For general cases, we use the delta between coordinates
  • Optimization: The formula accounts for the knight's movement constraints

Conclusion

This algorithm efficiently finds the minimum knight moves using mathematical optimization instead of BFS. The special cases handle edge scenarios, while the general formula works for larger distances using the knight's movement patterns.

Updated on: 2026-03-25T12:29:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements