0

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?

Tortar
  • 625
  • 5
  • 15

1 Answers1

0

Instead of putting True in the graph matrix, put a back-reference to the previous position in the graph (where you came from to get here). With that information you can find back the complete path you have travelled to get where you are.

Here is what to put in the if. Make sure to change also the one-but-last line of your shortest_path method:

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]:
                # Unwind graph information to build the path backwards to the start
                path = [[x,y], k]
                while k != start:
                    k = graph[k[0]][k[1]]
                    path.append(k)
                return path[::-1] # reverse
            if valid(x, y, n) and not graph[x][y]:
                graph[x][y] = k # store a back-reference here!
                queue.append([x,y])
trincot
  • 317,000
  • 35
  • 244
  • 286