Reorder Routes to Make All Paths Lead to the City Zero
LeetCode 1466 · Medium · solution, intuition & step-by-step walkthrough
DFS from 0 on the undirected graph; count edges pointing away.
This is how I solved Reorder Routes to Make All Paths Lead to the City Zero (LeetCode 1466), a medium problem from the Graph Fundamentals / DFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Walk outward from city 0 over the roads ignoring direction. Every road you traverse in its original direction points away from 0, so it must be reversed; roads you traverse backwards already point toward 0.
Approach
- 1
Undirected adjacency plus a set of original directed edges.
- 2
DFS from 0.
- 3
Moving node → neighbour along an original edge (node, neighbour) means it needs flipping.
- 4
Return the count.
How I solved it
DFS with edge directionsPythonO(n) time
class Solution:
def minReorder(self, n: int, connections: list[list[int]]) -> int:
"""
Intuition is if we start from zero/destination and go from destination that's not what we wanted. So that we need to reverse and count the number of reverses. We can maintain an undirected graph and directed graph set, will traverse from zero, if we can traverse from zero and that edge exists in directed graph set, we can think of it to reverse
"""
adj_list=defaultdict(list)
directed_edges = set()
for u,v in connections:
adj_list[u].append(v)
adj_list[v].append(u)
directed_edges.add((u,v))
visited = set()
count=0
def dfs(node):
nonlocal count
visited.add(node)
for adj_node in adj_list[node]:
if adj_node not in visited:
if (node,adj_node) in directed_edges:
count+=1
dfs(adj_node)
dfs(0)
return countReorder Routes to Make All Paths Lead to the City Zero — FAQ
What is the intuition behind Reorder Routes to Make All Paths Lead to the City Zero?
Walk outward from city 0 over the roads ignoring direction. Every road you traverse in its original direction points away from 0, so it must be reversed; roads you traverse backwards already point toward 0.
How do you solve Reorder Routes to Make All Paths Lead to the City Zero (LeetCode 1466)?
1. Undirected adjacency plus a set of original directed edges. 2. DFS from 0. 3. Moving node → neighbour along an original edge (node, neighbour) means it needs flipping. 4. Return the count.
What is the time and space complexity of Reorder Routes to Make All Paths Lead to the City Zero?
Time: O(n). Space: O(n). (Accepted approach: DFS with edge directions.)
What are common mistakes in Reorder Routes to Make All Paths Lead to the City Zero?
Count edges by their original direction, not the direction you travel.