Approach
Depth-first search
For Reorder Routes to Make All Paths Lead to the City Zero, 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
- 57 lines of Python from the credited upstream file reorder-routes-to-make-all-paths-lead-to-the-city-zero.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 minReorder(self, n, connections):9 """10 :type n: int11 :type connections: List[List[int]]12 :rtype: int13 """14 lookup, graph = set(), collections.defaultdict(list)15 for u, v in connections:16 lookup.add(u*n+v)17 graph[v].append(u)18 graph[u].append(v) 19 result = 020 stk = [(-1, 0)]21 while stk:22 parent, u = stk.pop()23 result += (parent*n+u in lookup)24 for v in reversed(graph[u]):25 if v == parent:26 continue27 stk.append((u, v))28 return result29 30 313233import collections34 35 36class Solution2(object):37 def minReorder(self, n, connections):38 """39 :type n: int40 :type connections: List[List[int]]41 :rtype: int42 """43 def dfs(n, lookup, graph, parent, u):44 result = (parent*n+u in lookup)45 for v in graph[u]:46 if v == parent:47 continue48 result += dfs(n, lookup, graph, u, v) 49 return result50 51 lookup, graph = set(), collections.defaultdict(list)52 for u, v in connections:53 lookup.add(u*n+v)54 graph[v].append(u)55 graph[u].append(v) 56 return dfs(n, lookup, graph, -1, 0)57