Advertisement
Eternoseeker

Ch-Assignment5-KnightsTour

Nov 24th, 2023
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | Source Code | 0 0
  1. def isSafe(x, y, board, n):
  2.     if x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1:
  3.         return True
  4.     return False
  5.  
  6. def printSolution(n, board):
  7.     for i in range(n):
  8.         for j in range(n):
  9.             print(board[i][j], end=' ')
  10.         print()
  11.  
  12. def solveKT(n):
  13.     board = [[-1 for i in range(n)] for i in range(n)]
  14.     move_x = [2, 1, -1, -2, -2, -1, 1, 2]
  15.     move_y = [1, 2, 2, 1, -1, -2, -2, -1]
  16.     board[0][0] = 0
  17.     pos = 1
  18.     if not solveKTUtil(n, board, 0, 0, move_x, move_y, pos):
  19.         print("Solution does not exist")
  20.     else:
  21.         printSolution(n, board)
  22.  
  23. def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos):
  24.     if pos == n ** 2:
  25.         return True
  26.     for i in range(8):
  27.         new_x = curr_x + move_x[i]
  28.         new_y = curr_y + move_y[i]
  29.         if isSafe(new_x, new_y, board, n):
  30.             board[new_x][new_y] = pos
  31.             if solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos + 1):
  32.                 return True
  33.             board[new_x][new_y] = -1
  34.     return False
  35.  
  36. if __name__ == "__main__":
  37.     n = int(input("Enter the size of the chessboard (n x n): "))
  38.     solveKT(n)
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement