Red Knight's Shortest Path

  • + 0 comments

    def is_valid(i, j, n): """ Check if the cell (i, j) is within the grid boundaries """ return 0 <= i < n and 0 <= j < n

    def get_neighbours(loc, n): """ Get valid neighboring cells and their corresponding move names """ i, j = loc[0], loc[1] name = ['UL', 'UR', 'R', 'LR', 'LL', 'L'] dr = [-2, -2, 0, 2, 2, 0] cr = [-1, 1, 2, 1, -1, -2] res = []

    for d in range(6):
        if is_valid(i + dr[d], j + cr[d], n):
            res.append([(i + dr[d], j + cr[d]), name[d]])
    
    return res
    

    def printShortestPath(n, i_start, j_start, i_end, j_end): """ Print the shortest path from (i_start, j_start) to (i_end, j_end) """

    # Dictionary to store parents of each cell and the move that led to them
    parent_dict = {(i_start, j_start): None}
    # Queue for BFS traversal
    front_tier = [(i_start, j_start)]
    # Next tier of cells to explore
    _next = []
    # Level counter for BFS
    lvl = 0
    # Target cell
    tgt = (i_end, j_end)
    
    def print_res(v):
        """ Recursively print the path using parent_dict """
        res = []
        cur = v
        while True:
            parent = parent_dict[cur]
            if parent is None:
                # Print in reverse order
                for i in range(len(res) - 1, -1, -1):
                    print(res[i], end=' ')
                return
            res.append(parent[1])
            cur = parent[0]
    
    while front_tier:
        for v in front_tier:
            if v == tgt:
                print(lvl)
                print_res(v)
                return
            neighbours = get_neighbours(v, n)
            for neighbour in neighbours:
                if neighbour[0] not in parent_dict:
                    _next.append(neighbour[0])
                    parent_dict[neighbour[0]] = [v, neighbour[1]]
    
        lvl += 1
        front_tier = _next
        _next = []
    
    print('Impossible')
    

    Reading input and calling the function

    if name == 'main': import os import sys input = sys.stdin.read data = list(map(int, input().strip().split()))

    n = data[0]
    i_start = data[1]
    j_start = data[2]
    i_end = data[3]
    j_end = data[4]
    
    printShortestPath(n, i_start, j_start, i_end, j_end)