Example #1
0
def find_distances(maze, inner_portals, outer_portals):
    """Calculate the distances between each portal using BFS."""
    distances = collections.defaultdict(dict)

    def update(pos, dist, state):
        if pos in inner_portals:
            portal = Portal(label=inner_portals[pos], is_inner=True)
            if state != portal:
                distances[state][portal] = dist
        elif pos in outer_portals:
            portal = Portal(label=outer_portals[pos], is_inner=False)
            if state != portal:
                distances[state][portal] = dist
        return state

    for inner, label in inner_portals.items():
        bfs(
            traversable_pred=lambda pos: maze[pos] == ".",
            start_node=inner,
            state_updater=update,
            initial_state=Portal(label, is_inner=True),
        )
    for outer, label in outer_portals.items():
        bfs(
            traversable_pred=lambda pos: maze[pos] == ".",
            start_node=outer,
            state_updater=update,
            initial_state=Portal(label, is_inner=False),
        )
    return distances
Example #2
0
def mark_paths(maze, start_pos, keys, doors, paths):
    """Calculate the length and passed keys/doors of the shortest paths from start_pos to every
    other key/door, assuming all the relevant doors are open. The results are written to paths
    as paths[start, end] = Path(...).
    """
    # Do a BFS tracking which doors/keys we've walked over
    State = collections.namedtuple("State", "doors keys")

    def update_state(position, distance, old_state):
        next_doors, next_keys = old_state.doors, old_state.keys
        # If we've moved and hit a door/key keep track of our state
        if distance > 0 and position in doors | keys:
            paths[start_pos, position] = Path(end=position,
                                              dist=distance,
                                              doors=next_doors,
                                              keys=next_keys)
            next_doors |= {position} & doors
            next_keys |= {position} & keys
        return State(next_doors, next_keys)

    bfs(
        state_updater=update_state,
        initial_state=State(doors=frozenset(), keys=frozenset()),
        traversable_pred=lambda pos: maze[pos] != "#",
        start_node=start_pos,
    )
Example #3
0
 def can_hit_target_from(self, user, map, target_loc):
     return bfs(map,
                target_loc,
                self.range,
                blockable=False,
                include_units=True,
                include_start=True)
Example #4
0
 def get_locs_in_range(self, user, map):
     return bfs(map,
                user.location,
                self.range,
                blockable=False,
                include_units=True,
                include_start=False)
Example #5
0
def part2(_, state):
    """Solve for the answer to part 2."""
    maze = state["maze"]
    station = state["station"]
    return bfs(
        traversable_pred=lambda pos: maze[pos] != HIT_WALL,
        start_node=station,
        initial_state=-1,
        state_updater=lambda pos, dist, curr_max: max(dist, curr_max),
    )
Example #6
0
def part1(program, state):
    """Solve for the answer to part 1."""
    robot = Robot(program)
    robot.explore()
    station = state["station"] = robot.station
    maze = state["maze"] = robot.maze
    distance, _ = bfs(
        traversable_pred=lambda pos: maze[pos] != HIT_WALL,
        start_node=(0, 0),
        end_node=station,
    )
    return distance
Example #7
0
def jump_to_room(destination, current_room=current_room):
    route_to_shop = bfs([current_room["room_id"]], destination, room_grid)
    routes = []

    for index in range(len(route_to_shop)):
        for direction in ["n", "e", "w", "s"]:
            try:
                if room_grid[str(
                        route_to_shop[index])][direction] == route_to_shop[
                            index + 1]:
                    routes.append(direction)
            except KeyError:
                None
            except IndexError:
                None

    count = 0

    while current_room["room_id"] != destination:
        for movement_direction in routes:
            if count < len(route_to_shop):
                time.sleep(current_room['cooldown'])
                new_room = requests.post(url + '/adv/move/',
                                         json={
                                             'direction':
                                             str(movement_direction),
                                             "next_room_id":
                                             str(route_to_shop[count])
                                         },
                                         headers={
                                             'Authorization': token
                                         }).json()
                current_room = new_room
                print(current_room)
                count += 1
            else:
                #exit()
                return


#jump_to_room('255')
Example #8
0
def find_near_unvisited_room(graph, current_room):
    # print("Current room in find_near_unvisited_room is " + str(current_room))
    path_unvisited = bfs(graph, current_room)
    # dfs option
    # path_unvisited = dfs(graph, current_room)

    # directions
    path = []

    for i in range(0, len(path_unvisited) - 1):
        list_graph = list(graph[path_unvisited[i]].items())

        nav = ""

        for x in list_graph:
            if x[1] == path_unvisited[i + 1]:
                nav = x[0]

        path.append(nav)

    return (path)
Example #9
0
#-*- coding:utf-8 -*-
import util


class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if root == None:
            return None
        tmpleft = root.left
        root.left = self.Mirror(root.right)
        root.right = self.Mirror(tmpleft)
        return root


n1 = [8, 8, 7, 9, 2, '#', '#', '#', '#', 4, 7]
nums = [8, 9, 2]
root1 = util.BuildTree(n1, 1)
root2 = util.BuildTree(nums, 1)
s = Solution()
print util.bfs(s.Mirror(root1))
print util.bfs(s.Mirror(root2))
Example #10
0
    direction = None

    ud = unexplored_directions(player_graph, player.current_room.id)

    if len(player.current_room.get_exits()) == 1:
        #pops the direction, removes it and returns it
        direction = player.current_room.get_exits().pop()

    elif len(ud) > 1:
        #returns unexplored direction
        direction = ud.pop()

    #visit unexplored rooms
    elif len(ud) == 0:
        nr = find_unexplored_room(player_graph)
        path = bfs(player, player.current_room.id, nr, player_graph)
        path = path[1:]
        while len(path) > 0:
            next_room = path.pop(0)
            direction = find_room_direction(
                player_graph[player.current_room.id], next_room)
            if len(path) > 0:
                previous_room = player.current_room.id
                player.travel(direction)
                traversal_path.append(direction)
                visited_rooms_list.append(player.current_room.id)

    if direction is None:
        for key, value in player_graph[player.current_room.id].items():
            if (key in ["n", "s", "e", "w"]) and (value == "?"):
                direction = key
Example #11
0
 def can_hit_target_from(self, user, map, target_loc):
     return bfs(map, target_loc, self.range, blockable=False, include_units = True, include_start=True)
Example #12
0
 def get_locs_in_range(self, user, map):
     return bfs(map, user.location, self.range, blockable=False, include_units = True, include_start=False)