KatInterview

Reach the Goal State While Avoiding Forbidden Nodes

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsgraphbfsreachability

Last 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 if goal == 0 the answer is True (provided 0 is not hazardous).
  • If state 0 or goal appears in hazards, return False. 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 from v to u.
  • transitions may contain duplicates and self-loops. hazards may 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 goal is reachable matters.

Input

  • n: the number of states.
  • transitions: a list of [u, v] pairs, each a directed move from u to v.
  • 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^5
  • 0 <= len(transitions) <= 2 * 10^5
  • Every state in transitions, hazards and goal is in the range [0, n - 1].
  • 0 is never in hazards.
  • goal is never in hazards.

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.