Skip to content

Commit 8c4b4c4

Browse files
authored
Create Knight's Tour Problem.py
1 parent 59afa1d commit 8c4b4c4

File tree

1 file changed

+79
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)