the code so far only displays an integer of the minimum steps the knight took to reach the target but how can i display that and all the moves coordinates that it took to reach said target position whilst avoiding the trap coordinates and still finding the shortest path?
i've tried different ways to code the trap location in but i keep getting errors so id really appreciate help
thank you!
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 movements 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 until 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 = int(input("input integer n (n≥8): "))
while N<8:
N = int(input("input out of range, please input again: "))
#line2
a, b = input("input starting location a, b : ").split()
a= int(a)
b= int(b)
while (1>a or a>N) or (1>b or b>N):
a, b = input("input out of range, please input again: ").split()
a= int(a)
b= int(b)
while (1>a or a>N) or (1>b or b>N):
a, b = input("input out of range, please input again: ").split()
a= int(a)
b= int(b)
knightpos = [a, b]
c, d = input("input ending location c, d : ").split()
c= int(c)
d= int(d)
while (1>c or c>N) or (1>d or d>N):
c, d = input("input out of range, please input again: ").split()
c= int(c)
d= int(d)
targetpos = [c, d]
m = int(input("input integer m: "))
if m==0:
pass
else:
trapLocation = []
trap_length = m
for idx in range(trap_length):
x = int(input("input trap location x coordinate: "))
y = int(input("input trap location y coordinate: "))
trapLocation.append((x, y))
startPoint = (a,b)
if startPoint in trapLocation:
print("No")
pass
else:
print("Yes")
print(minStepToReachTarget(knightpos, targetpos, N))