我编写了此代码,可以解决骑士的最短路径问题。问题是我不知道如何计算它在图形上达到的深度级别。
# 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,1,-1,-1]
dy = [1,-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,n):
if 0 <= x <= n-1 :
if 0 <= y <= n-1 :
return True
return False
我应该在代码中添加什么?