I have made this code which should solve the knight's shortest path problem . The problem is that I don't know how to count the depth level it reaches on the graph.
# n = size of the board
# start = starting position for example [0,0]
# end = ending position
def shortest_path(start , end , n ):
dx = [2, 2, -2, -2, 1, 1, -1, -1]
dy = [1, -1, 1, -1, 2, -2, 2, -2]
graph = [[False for x in range(n)]for x in range(n)]
graph[start[0]][start[1]] = True
queue = []
queue.append(start)
while len(queue)> 0 :
k = queue[0]
queue.pop(0)
for s in range(8):
x = k[0] + dx[s]
y = k[1] + dy[s]
if x == end[0] and y == end[1] :
return ????
if valid(x , y ,n) and not graph[x][y] :
graph[x][y] = True
queue.append([x,y])
def valid(x , y ,n):
if 0 <= x <= n-1 :
if 0 <= y <= n-1 :
return True
return False
What should I add to the code?