Skip to content

Commit 35892cb

Browse files
authored
Merge pull request #527 from Manasi2001/issue-526
Knight's Tour
2 parents 169db3d + ea3ece8 commit 35892cb

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Backtracking/Knight's_Tour.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
'''
2+
Aim: To check whether it is possible for a Knight to visit each
3+
cell of the N*N chessboard without visiting any cell
4+
twice starting from (X, Y) position.
5+
Intution: To visit each and every positions which are available from
6+
the current position and recursively repeat this until
7+
all the cells are covered.
8+
9+
'''
10+
11+
from time import time
12+
13+
14+
def move_Knight(n, pos, move, ans, step):
15+
x, y = pos
16+
17+
# Base Case
18+
if step == n * n:
19+
return ans
20+
for i in move:
21+
r = x + i[0]
22+
c = y + i[1]
23+
if 0 <= r < n and 0 <= c < n and not ans[r][c]:
24+
ans[r][c] = step + 1
25+
temp = move_Knight(n, (r, c), move, ans, step + 1)
26+
if temp is not False:
27+
return temp
28+
ans[r][c] = 0
29+
return False
30+
31+
32+
def Knight_Tour(n, pos):
33+
x, y = pos
34+
35+
# All valid moves that a Knight can make
36+
move = [[2, 1], [2, -1], [-2, 1], [-2, -1],
37+
[1, 2], [1, -2], [-1, 2], [-1, -2]]
38+
39+
# To keep a track of already visited cells and
40+
# Answer Matrix
41+
answer = [[0]*n for i in range(n)]
42+
43+
# To mark (X, Y) cell as visited
44+
answer[x][y] = 1
45+
46+
return move_Knight(n, pos, move, answer, 1)
47+
48+
49+
# ------------------------DRIVER CODE ------------------------
50+
51+
if __name__ == "__main__":
52+
53+
# Input the initial Position of the Knight
54+
N = int(input("Enter the size of the Chessboard: "))
55+
X, Y = map(int, input("Enter Initial Position of the Knight: ").split())
56+
start = time()
57+
ans_mat = Knight_Tour(N, (X-1, Y-1))
58+
if ans_mat is False:
59+
print("Knight's Tour form the given initial position is not possible")
60+
else:
61+
print("The desired Knight's Tour :")
62+
for i in ans_mat:
63+
print("\t\t", *i)
64+
print("Time taken: ", time()-start)
65+
66+
'''
67+
68+
Sample Working:
69+
70+
Enter the size of the Chessboard: 5
71+
Enter the Initial Position of the Knight: 1 1
72+
The desired Knight's Tour :
73+
1 6 15 10 21
74+
14 9 20 5 16
75+
19 2 7 22 11
76+
8 13 24 17 4
77+
25 18 3 12 23
78+
Time taken: 0.10171318054199219
79+
80+
COMPLEXITY:
81+
82+
Time Complexity -> O(8^N)
83+
Space Complexity -> O(N^2)
84+
85+
'''

0 commit comments

Comments
 (0)