Python
Python

 

 

The Knight’s Tour is a classic problem in which a knight must visit every square on a chessboard exactly once. The knight moves in an L-shape: two squares in one direction and one square perpendicular. The challenge is to find a sequence of moves that allows the knight to cover the entire board.

Program Structure

The program uses a backtracking algorithm to explore all possible moves of the knight. It employs recursion to attempt each move, backtracking when a move leads to a dead end. The main components of the program are:

  • Constants: The size of the chessboard and the possible moves a knight can make.
  • Utility Functions: Functions to check if a move is valid and to print the solution.
  • Backtracking Function: A recursive function that tries to place the knight on the board and checks for valid moves.
  • Driver Function: Initializes the board and starts the knight’s tour.

Python Code


def print_solution(n, board):
    """Function to print the chessboard."""
    for row in board:
        print(" ".join(str(cell).rjust(2, ' ') for cell in row))
    print()

def is_safe(x, y, n, board):
    """Check if the knight's move is valid."""
    return 0 <= x < n and 0 <= y < n and board[x][y] == -1

def knight_tour_util(n, board, curr_x, curr_y, movei, x_moves, y_moves):
    """Utility function to solve the Knight's Tour problem using backtracking."""
    if movei == n * n:
        return True

    for i in range(8):
        next_x = curr_x + x_moves[i]
        next_y = curr_y + y_moves[i]
        if is_safe(next_x, next_y, n, board):
            board[next_x][next_y] = movei
            if knight_tour_util(n, board, next_x, next_y, movei + 1, x_moves, y_moves):
                return True
            # Backtracking
            board[next_x][next_y] = -1

    return False

def knight_tour(n):
    """Driver function to initialize the board and start the Knight's Tour."""
    # Initialize the board
    board = [[-1 for _ in range(n)] for _ in range(n)]

    # Possible moves of a knight
    x_moves = [2, 1, -1, -2, -2, -1, 1, 2]
    y_moves = [1, 2, 2, 1, -1, -2, -2, -1]

    # Start from the first square
    board[0][0] = 0

    if not knight_tour_util(n, board, 0, 0, 1, x_moves, y_moves):
        print("Solution does not exist")
    else:
        print_solution(n, board)

# Set the size of the chessboard
n = 8
knight_tour(n)

How to Run the Program

To run the program:

  1. Copy the code into a Python file (e.g., knights_tour.py).
  2. Run the file using Python 3: python knights_tour.py.
  3. The program will print the chessboard with the knight’s tour solution, if one exists.

Conclusion

The Knight’s Tour problem is an excellent example of backtracking in algorithms. This program effectively demonstrates how to explore all possible knight moves and backtrack to find a valid tour of the chessboard.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)