-
Notifications
You must be signed in to change notification settings - Fork 274
/
The_Knight’s_tour.py
85 lines (66 loc) · 2.2 KB
/
The_Knight’s_tour.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Chessboard Size
n = 8
def isSafe(x, y, board):
'''
A utility function to check if i,j are valid indexes
for N*N chessboard
'''
if(x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1):
return True
return False
def printSolution(n, board):
'''
A utility function to print Chessboard matrix
'''
for i in range(n):
for j in range(n):
print(board[i][j], end=' ')
print()
def solveKT(n):
'''
This function solves the Knight Tour problem using
Backtracking. This function mainly uses solveKTUtil()
to solve the problem. It returns false if no complete
tour is possible, otherwise return true and prints the
tour.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions.
'''
# Initialization of Board matrix
board = [[-1 for i in range(n)]for i in range(n)]
# move_x and move_y define next move of Knight.
# move_x is for next value of x coordinate
# move_y is for next value of y coordinate
move_x = [2, 1, -1, -2, -2, -1, 1, 2]
move_y = [1, 2, 2, 1, -1, -2, -2, -1]
# Since the Knight is initially at the first block
board[0][0] = 0
# Step counter for knight's position
pos = 1
# Checking if solution exists or not
if(not solveKTUtil(n, board, 0, 0, move_x, move_y, pos)):
print("Solution does not exist")
else:
printSolution(n, board)
def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos):
'''
A recursive utility function to solve Knight Tour
problem
'''
if(pos == n**2):
return True
# Try all next moves from the current coordinate x, y
for i in range(8):
new_x = curr_x + move_x[i]
new_y = curr_y + move_y[i]
if(isSafe(new_x, new_y, board)):
board[new_x][new_y] = pos
if(solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos+1)):
return True
# Backtracking
board[new_x][new_y] = -1
return False
# Driver Code
if __name__ == "__main__":
# Function Call
solveKT(n)