• + 0 comments

    from collections import deque

    def minimumMoves(grid, startX, startY, goalX, goalY): n = len(grid) directions = ( (-1, 0), (0, 1), (1, 0), (0, -1), ) queue = deque( [(startX, startY, 0)] ) visited = set( [(startX, startY)] )

    # BFS
    while queue:
        current_x, current_y, current_distance = queue.popleft()
    
        if (current_x, current_y) == (goalX, goalY):
            return current_distance
    
        # Visit current node neighbors
        for move_to_x, move_to_y in directions:
            next_x, next_y = current_x, current_y
    
            # Move until reaching grid's edge or facing an obstacle "X"
            while (
                0 <= next_x + move_to_x < n
                and 0 <= next_y + move_to_y < n
                and grid[next_x + move_to_x][next_y + move_to_y]
                != "X"
            ):
                next_x += move_to_x
                next_y += move_to_y
    
    
                if (next_x, next_y) == (goalX, goalY):
                    return current_distance + 1
    
            if (next_x, next_y) not in visited:
                visited.add((next_x, next_y))
                queue.append((next_x, next_y, current_distance + 1))
    
    return -1