KatInterview

List Every Non-Repeating Route in a Directed Graph

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraphdfsbacktracking

Last updated

Enumerate all routes from a source to a target in a directed graph that never revisit a node, returned in lexicographic order, using backtracking DFS.

You are given a directed graph as an adjacency mapping. Each key is a node, and its value is the list of nodes reachable from it by one outgoing edge. Given a source node and a target node, return every route from source to target in which no node appears more than once.

Output rules:

  • Each route is a list of nodes, starting with source and ending with target.
  • Return the routes sorted in lexicographic order, comparing them element by element as lists of integers.
  • If no such route exists, return an empty list.

Details to handle:

  • Node identifiers in the mapping's keys may be given as strings (for example "3") while the neighbor lists contain integers. Treat a key such as "3" as the node 3.
  • A node that appears only as a neighbor, and not as a key, has no outgoing edges.
  • If source == target, the only valid route is the single-node route [source]. Returning to the source through a cycle would repeat a node, so it is not allowed.
  • A route stops as soon as it reaches target; it can never continue past it, since that would require visiting target again.
  • Duplicate entries in a neighbor list or self-loops must not produce duplicate routes or invalid routes.
  • The graph may contain cycles.

Constraints

  • The graph has at most 20 nodes.
  • graph[u] lists the direct successors of u.
  • Node identifiers are integers (possibly given as string keys in the mapping).
  • Each returned route contains no repeated node.

Examples

Example 1

Input: list_simple_routes({'0': [1, 2], '1': [2], '2': [0, 3], '3': []}, 0, 3)

Output: [[0, 1, 2, 3], [0, 2, 3]]

Example 2

Input: list_simple_routes({'0': [1], '1': [2], '2': []}, 0, 2)

Output: [[0, 1, 2]]

Hints

Hint 1

Think of building a route one node at a time, keeping track of which nodes are already on the current route. Undo each choice after exploring it.

Hint 2

The 'already used' marker must apply only to the route currently being built, not to the whole search, otherwise a node could never appear in two different routes.

Hint 3

When you reach the target, record a copy of the current route and stop extending it. Visit neighbors in sorted, de-duplicated order so results come out in lexicographic order, and normalize string keys to integers first.