List Every Non-Repeating Route in a Directed Graph
Trees & GraphsAuto-graded · 18 test casesLast 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
sourceand ending withtarget. - 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 node3. - 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 visitingtargetagain. - 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 ofu.- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use depth-first search with backtracking. Maintain the current route as a list and a set of the nodes on it. From the current node, try each unvisited neighbor: add it to the route, recurse, then remove it (backtrack).
Before searching, normalize the input: convert keys and neighbors to integers, and replace each neighbor list with its sorted, de-duplicated version. Nodes missing from the mapping are treated as having no outgoing edges.
When the DFS arrives at target, it saves a copy of the current route and returns immediately. Extending further would require revisiting target, which is not allowed.
Why it is correct
- Only simple routes are reported: a neighbor is only added when it is not already on the current route.
- Every simple route is found: consider any simple route
source = p0, p1, ..., pk = target. Eachp(i+1)is a neighbor ofp(i)and is not among the earlier nodes, so the DFS follows exactly that branch. No earlier node equalstarget, so the search never stops early along it. - No duplicates: de-duplicated neighbors mean each distinct node sequence corresponds to exactly one branch of the recursion.
- Ordering: neighbors are visited in ascending order, so routes are already produced lexicographically; the final sort is a harmless safeguard.
source == target: the DFS records[source]immediately and returns, which matches the required rule.- Marker scope: the on-route set is per route (added and removed during backtracking), so a node can appear in several different routes.
Complexity
Let P be the number of valid routes and V the number of nodes.
- Time: O(V * P) to copy routes into the output, plus the cost of exploring dead-end branches. In the worst case (dense graphs) this is factorial in
V, which is unavoidable since the output itself can be that large. - Space: O(V) for the recursion stack and route state, plus the output size.
Reference solution
from typing import Dict, List
def list_simple_routes(graph: Dict[int, List[int]], source: int, target: int) -> List[List[int]]:
# Keys may arrive as strings (e.g. from JSON), so normalize to ints.
adjacency = {int(node): sorted(set(map(int, neighbors)))
for node, neighbors in graph.items()}
routes: List[List[int]] = []
route = [source]
on_route = {source}
def dfs(node: int) -> None:
if node == target:
routes.append(route.copy())
return
for nxt in adjacency.get(node, []):
if nxt in on_route:
continue
on_route.add(nxt)
route.append(nxt)
dfs(nxt)
route.pop()
on_route.remove(nxt)
dfs(source)
routes.sort()
return routes