-
Notifications
You must be signed in to change notification settings - Fork 0
/
KnightStartToFinishMinimumSteps.py
53 lines (41 loc) · 1.25 KB
/
KnightStartToFinishMinimumSteps.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
class cell:
def __init__(self, x = 0, y = 0, dist = 0):
self.x = x
self.y = y
self.dist = dist
def isInside(x, y, N):
if (x >= 1 and x <= N and
y >= 1 and y <= N):
return True
return False
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))
if __name__ == '__main__':
N = 30
knightpos = [1, 1]
targetpos = [30, 30]
print(minStepToReachTarget(knightpos, targetpos, N))