Advertisement
Eternoseeker

S-Ass5-KnightsTour

Nov 24th, 2023
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | Source Code | 0 0
  1. n = int(input("Enter the size of the chessboard (>4): "))
  2.  
  3. def isSafe(x, y, board):
  4.         #A utility function to check if i,j are valid indexes  
  5.         #for N*N chessboard
  6.     if(x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1):
  7.         return True
  8.     return False
  9.  
  10. def printSolution(n, board):
  11.     #A utility function to print Chessboard matrix
  12.     for i in range(n):
  13.         for j in range(n):
  14.             print(board[i][j], end = ' ')
  15.         print()
  16.  
  17. def solveKT(n):
  18.     #A recursive utility function to solve Knight Tour problem
  19.     #using backtracking
  20.     #Initialization of the chessboard
  21.     board = [[-1 for i in range(n)]for i in range(n)]
  22.     #move_x and move_y define next move of Knight.
  23.     #move_x is for next value of x coordinate
  24.     #move_y is for next value of y coordinate
  25.     move_x = [2, 1, -1, -2, -2, -1, 1, 2]
  26.     move_y = [1, 2, 2, 1, -1, -2, -2, -1]
  27.     #Since the Knight is initially at the first block
  28.     board[0][0] = 0
  29.     #Step counter for knight's position
  30.     pos = 1
  31.     #Checking if solution exists or not
  32.     if(not solveKTUtil(n, board, 0, 0, move_x, move_y, pos)):
  33.         print("Solution does not exist")
  34.     else:
  35.         print("The order of the cells visited: ")
  36.         printSolution(n, board)
  37.  
  38. def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos):
  39.     #A recursive utility function to solve Knight Tour problem
  40.     #using backtracking
  41.     if(pos == n**2):
  42.         return True
  43.     #Try all next moves from the current coordinate x, y
  44.     for i in range(8):
  45.         new_x = curr_x + move_x[i]
  46.         new_y = curr_y + move_y[i]
  47.         if(isSafe(new_x, new_y, board)):
  48.             board[new_x][new_y] = pos
  49.             if(solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos+1)):
  50.                 return True
  51.             #Backtracking
  52.             board[new_x][new_y] = -1
  53.     return False
  54.  
  55. #Driver Code
  56. if __name__ == "__main__":
  57.     solveKT(n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement