-
Notifications
You must be signed in to change notification settings - Fork 0
/
KnightMoves.py
73 lines (55 loc) · 1.74 KB
/
KnightMoves.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
# Python3 code to find minimum steps to reach
# to specific cell in minimum moves by Knight
class cell:
def __init__(self, x=0, y=0, dist=0):
self.x = x
self.y = y
self.dist = dist
# checks whether given position is
# inside the board
def isInside(x, y, N):
if (x >= 1 and x <= N and
y >= 1 and y <= N):
return True
return False
# Method returns minimum step to reach
# target position
def minStepToReachTarget(knightpos,
targetpos, N):
# all possible movments for the knight
dx = [2, 2, -2, -2, 1, 1, -1, -1]
dy = [1, -1, 1, -1, 2, -2, 2, -2]
queue = []
# push starting position of knight
# with 0 distance
queue.append(cell(knightpos[0], knightpos[1], 0))
# make all cell unvisited
visited = [[False for i in range(N + 1)]
for j in range(N + 1)]
# visit starting state
visited[knightpos[0]][knightpos[1]] = True
# loop untill we have one element in queue
while (len(queue) > 0):
t = queue[0]
queue.pop(0)
# if current cell is equal to target
# cell, return its distance
if (t.x == targetpos[0] and
t.y == targetpos[1]):
return t.dist
# iterate for all reachable states
for i in range(8):
x = t.x + dx[i]
y = t.y + dy[i]
if (isInside(x, y, N) and not visited[x][y]):
visited[x][y] = True
queue.append(cell(x, y, t.dist + 1))
# Driver Code
if __name__ == '__main__':
N = 8
knightpos = [1, 1]
targetpos = [8, 8]
print(minStepToReachTarget(knightpos,
targetpos, N))
# This code is contributed by
# Kaustav kumar Chanda