Approach
Depth-first search
For All Paths from Source Lead to Destination, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 36 lines of Python from the credited upstream file all-paths-from-source-lead-to-destination.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 7class Solution(object):8 def leadsToDestination(self, n, edges, source, destination):9 """10 :type n: int11 :type edges: List[List[int]]12 :type source: int13 :type destination: int14 :rtype: bool15 """16 UNVISITED, VISITING, DONE = range(3)17 def dfs(children, node, destination, status):18 if status[node] == DONE:19 return True20 if status[node] == VISITING:21 return False22 status[node] = VISITING23 if node not in children and node != destination:24 return False25 if node in children:26 for child in children[node]:27 if not dfs(children, child, destination, status):28 return False29 status[node] = DONE30 return True31 32 children = collections.defaultdict(list)33 for parent, child in edges:34 children[parent].append(child)35 return dfs(children, source, destination, [0]*n)36