Reach the Goal State While Avoiding Forbidden Nodes
Trees & GraphsAuto-graded · 21 test casesLast updated
Decide whether a goal node can be reached from node 0 in a directed graph without ever stepping on a forbidden node, using BFS or DFS reachability.
Safe Route Through a State Machine
A machine has n states, numbered 0 to n - 1. You start in state 0. Each entry [u, v] in transitions is a one-way move from state u to state v.
Some states are hazardous, and they are listed in hazards. Entering a hazardous state ends the run immediately, so a valid route may never visit one.
Return True if some sequence of transitions leads from state 0 to state goal and never visits a hazardous state. Otherwise return False.
Rules
- A route is a sequence of states starting at
0, where each consecutive pair is a listed transition. A route of length zero is allowed, so ifgoal == 0the answer isTrue(provided0is not hazardous). - If state
0orgoalappears inhazards, returnFalse. The constraints below rule this out, but the rule applies if it ever occurs. - Transitions are directed. A transition
[u, v]does not let you move fromvtou. transitionsmay contain duplicates and self-loops.hazardsmay contain duplicates. None of these change the answer.- Transitions that start at a hazardous state are irrelevant, because you can never be in such a state.
- Cycles are allowed in the graph. Only whether
goalis reachable matters.
Input
n: the number of states.transitions: a list of[u, v]pairs, each a directed move fromutov.hazards: a list of states that must not be entered.goal: the state you want to reach.
Output
A boolean: True if a hazard-free route from 0 to goal exists, otherwise False.
Constraints
2 <= n <= 10^50 <= len(transitions) <= 2 * 10^5- Every state in
transitions,hazardsandgoalis in the range[0, n - 1]. 0is never inhazards.goalis never inhazards.
Examples
Example 1
Input: can_reach_goal(4, [[0, 1], [1, 2], [2, 3]], [1], 3)
Output: False
Example 2
Input: can_reach_goal(5, [[0, 1], [0, 2], [2, 3], [2, 4]], [1], 4)
Output: True
Hints
Hint 1
Think of a hazardous state as a node you are not allowed to enter, which is the same as deleting it from the graph. What question remains once it is gone?
Hint 2
Run a BFS or DFS from state 0. Keep a visited array, and skip any neighbor that is visited or hazardous. Pre-marking hazardous states as visited handles both checks at once.
Hint 3
Use an iterative traversal rather than recursion, since a chain of 10^5 states could exceed Python's recursion limit. Also remember that goal == 0 is already solved.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the states as nodes of a directed graph and the transitions as directed edges. A hazardous state can never be entered, so it behaves as if it had been removed from the graph. The task becomes plain reachability: is goal reachable from 0 in the graph that remains?
A breadth-first search answers this:
- If
0orgoalis hazardous, returnFalse. - Build an adjacency list from
transitions. - Put the hazards in a set so membership checks are O(1).
- Start a BFS from state
0. When a state is dequeued, returnTrueif it is the goal. - Otherwise, enqueue each neighbor that is neither visited nor hazardous, and mark it visited.
- If the queue empties without reaching the goal, return
False.
The check on dequeue also covers goal == 0, since the start state is dequeued first.
Why it is correct
- No hazard is ever entered. A hazardous neighbor is never enqueued, so every state the search explores lies in the hazard-free part of the graph.
- A safe route is always found. Suppose a safe route
0 = s0 -> s1 -> ... -> sk = goalexists.s0is enqueued first. Whensiis processed, its neighbors(i+1)is safe, so it is either already visited, and thus already queued, or it gets enqueued now. By induction everysiis eventually dequeued, including the goal. - Cycles and duplicates are harmless. Each state is enqueued at most once because of the visited array, so self-loops, repeated edges and cycles cannot cause repeated work or an infinite loop.
BFS is iterative, so long chains do not hit Python's recursion limit.
Complexity
- Time:
O(n + E), whereEis the number of transitions. Building the graph and running the search each touch every node and edge at most once. - Space:
O(n + E)for the adjacency list, plusO(n)for the visited array, the queue and the hazard set.
Reference solution
from collections import deque
from typing import List
def can_reach_goal(n: int, transitions: List[List[int]], hazards: List[int], goal: int) -> bool:
blocked = set(hazards)
if 0 in blocked or goal in blocked:
return False
graph = [[] for _ in range(n)]
for u, v in transitions:
graph[u].append(v)
visited = [False] * n
visited[0] = True
queue = deque([0])
while queue:
state = queue.popleft()
if state == goal:
return True
for nxt in graph[state]:
if not visited[nxt] and nxt not in blocked:
visited[nxt] = True
queue.append(nxt)
return False