Find the Exit of a Keyed Forest Graph
Trees & GraphsAuto-graded · 15 test casesLast updated
Run a breadth-first search over (location, keys held) states in a forest with locked doors to find the first exit reached, or None.
Forest Exit with Locked Doors
A forest is described by a list of location records. You move through it by following links from one location to another, and you must find an exit.
Each record is a dictionary with these fields:
id(string): the unique name of the location.message(string, optional): a location is an exit exactly whenmessage == "DONE".neighbors(list, optional, default empty): outgoing links. Each link is a dictionary with:url(string): looks like/mirkwood?location=B. The destination id is the value of thelocationquery parameter.direction(string, optional): informational only.locked(boolean, optional, defaultfalse): whether the door is locked.required_key(string, optional): the key needed to pass if the door is locked.
keys(list of strings, optional, default empty): keys picked up automatically upon arriving at this location.
Movement rules
- You start at the location
start_id. You collect that location's keys immediately. - Keys are never lost. Arriving at a location adds its
keysto your collection. - A link with
lockedtrue can only be used ifrequired_keyis present and you already hold that key. Hold means you have it before crossing, including keys from the location you are standing on. A locked link with norequired_keycan never be used. - A link is ignored if its
urlhas no non-emptylocationquery parameter, or if that id does not exist among the records. If the parameter appears several times, use the first value. - Locations may be revisited when you hold a different set of keys than before, since that can open new doors. The same location with the same set of keys is never processed twice.
Search order
Explore shallow positions before deep ones with a breadth-first search over states (location id, set of keys held):
- Begin with the single state for
start_id. - Take states from a first-in-first-out queue. When a state is taken out, check whether its location is an exit. If so, return that location's id.
- Otherwise, go through the location's
neighborsin the listed order, and for each usable link, compute the new state. If it has not been seen before, add it to the back of the queue.
Task
Implement find_forest_exit(rooms, start_room), which returns the id of the exit found first under the order above, or None if no exit can be reached, or if start_room is not one of the records.
Constraints
- 0 ≤ number of locations ≤ 2000, and location ids are unique.
- Each location has at most 20 neighbors and at most 10 keys.
- The total number of distinct keys across the forest is at most 10.
- Ids and key names are non-empty strings.
- Links may form cycles and self-loops.
Examples
Example 1
Input: find_forest_exit([{'id': 'A', 'neighbors': [{'direction': 'north', 'url': '/mirkwood?location=B'}, {'direction': 'east', 'url': '/mirkwood?location=C'}]}, {'id': 'B', 'neighbors': [{'direction': 'north', 'url': '/mirkwood?location=Z'}]}, {'id': 'C', 'neighbors': [{'direction': 'east', 'url': '/mirkwood?location=Z'}]}, {'id': 'Z', 'message': 'DONE', 'neighbors': []}], 'A')
Output: 'Z'
Example 2
Input: find_forest_exit([{'id': 'A', 'neighbors': [{'url': '/mirkwood?location=B'}, {'url': '/mirkwood?location=C'}]}, {'id': 'B', 'neighbors': [{'url': '/mirkwood?location=Z'}]}, {'id': 'C', 'neighbors': [{'url': '/mirkwood?location=Z'}]}, {'id': 'Z', 'message': 'DONE', 'neighbors': []}], 'A')
Output: 'Z'
Hints
Hint 1
Think of the search state as a pair: the current location and the set of keys you hold. The same location with different key sets can behave differently.
Hint 2
Use a FIFO queue and a visited set of (location, frozenset of keys). Check for the exit when you remove a state from the queue, and add the new location's keys when you move into it.
Hint 3
Extract the destination with a URL parser (parse_qs on the query string). Skip links without a usable location, with an unknown id, or locked without the right key already held.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A plain location graph is not enough, because whether a locked door is passable depends on which keys you have collected so far. So the search state is a pair (location id, frozenset of keys held).
- Index the records by id. If
start_roomis unknown, returnNone. - Start from the start location with the keys found there.
- Run a standard BFS with a FIFO queue. When a state is dequeued, return its location id if the message is
"DONE". - For each link, in the listed order:
- If it is locked, skip it unless
required_keyexists and is in the current key set. - Parse the destination id from the
locationquery parameter, and skip the link if it is missing or unknown. - The new key set is the old one plus the keys at the destination. Enqueue the new state if it has not been seen.
- If it is locked, skip it unless
- If the queue empties, no exit is reachable, so return
None.
Why it is correct
- Keys only accumulate, and the key set is part of the state. Therefore every route that is legal under the key rules corresponds to a path in the state graph, and vice versa.
- BFS dequeues states in non-decreasing distance from the start, so shallower positions are examined first. Fixed neighbor order and FIFO queueing make the returned exit deterministic.
- The
seenset guarantees that each state is enqueued at most once, which handles cycles and self-loops, and the finite number of states guarantees termination. - Revisiting a location with more keys is a different state, so doors that were previously blocked are tried again.
Complexity
Let V be the number of locations, D the maximum number of links per location, and K the number of distinct keys. There are at most V · 2^K states, and each is expanded in O(D) time (plus key-set union of size at most K). So the time is O(V · 2^K · D) in the worst case and the space is O(V · 2^K). In practice the number of reachable key sets is much smaller, since a key set is determined by the path taken.
Reference solution
from collections import deque
from typing import Dict, List, Optional
from urllib.parse import parse_qs, urlparse
def find_forest_exit(rooms: List[Dict], start_room: str) -> Optional[str]:
by_id = {room["id"]: room for room in rooms}
if start_room not in by_id:
return None
start_keys = frozenset(by_id[start_room].get("keys", []))
queue = deque([(start_room, start_keys)])
seen = {(start_room, start_keys)}
while queue:
room_id, keys = queue.popleft()
room = by_id[room_id]
if room.get("message") == "DONE":
return room_id
for link in room.get("neighbors", []):
if link.get("locked", False):
needed = link.get("required_key")
if needed is None or needed not in keys:
continue
values = parse_qs(urlparse(link["url"]).query).get("location", [])
if not values:
continue
next_id = values[0]
if next_id not in by_id:
continue
next_keys = keys | frozenset(by_id[next_id].get("keys", []))
state = (next_id, next_keys)
if state not in seen:
seen.add(state)
queue.append(state)
return None