Reorder Routes to Make All Paths Lead to the City Zero - Problem
Imagine a country with
The roads are represented by
Now there's a major event happening in the capital city
Goal: Return the minimum number of edge directions that must be changed.
Note: It's guaranteed that after reordering, every city will be able to reach city
n cities numbered from 0 to n-1, connected by exactly n-1 roads forming a tree structure (meaning there's exactly one path between any two cities). The government has decided to make all roads one-way due to narrow width constraints.The roads are represented by
connections where connections[i] = [ai, bi] indicates a directed road from city ai to city bi.Now there's a major event happening in the capital city
0, and everyone wants to travel there! Your task is to find the minimum number of roads that need to be reversed so that every city has a path leading to city 0.Goal: Return the minimum number of edge directions that must be changed.
Note: It's guaranteed that after reordering, every city will be able to reach city
0. Input & Output
example_1.py โ Basic Tree
$
Input:
n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
โบ
Output:
3
๐ก Note:
We need to reverse 3 edges: [1,3] becomes [3,1], [2,3] becomes [3,2], and [4,5] becomes [5,4] so all cities can reach city 0.
example_2.py โ Linear Chain
$
Input:
n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
โบ
Output:
2
๐ก Note:
We need to reverse 2 edges: [3,2] becomes [2,3] and [3,4] becomes [4,3] to allow all cities to reach city 0.
example_3.py โ Already Optimal
$
Input:
n = 3, connections = [[1,0],[2,0]]
โบ
Output:
0
๐ก Note:
All roads already point toward city 0, so no reversals are needed.
Visualization
Tap to expand
Understanding the Visualization
1
Build undirected graph
Create adjacency list with both directions but remember original edge directions
2
Start DFS from city 0
Begin depth-first search from the capital city
3
Count wrong directions
For each edge traversed, if it was originally pointing away from city 0, increment counter
4
Return total count
The counter represents minimum edges to reverse
Key Takeaway
๐ฏ Key Insight: Instead of finding paths from each city to the capital, start from the capital and traverse the tree once, counting edges that point away from the root!
Time & Space Complexity
Time Complexity
O(nยฒ)
For each of n cities, we might traverse up to n edges to find path to city 0
โ Quadratic Growth
Space Complexity
O(n)
Space for visited array and recursion stack in worst case
โก Linearithmic Space
Constraints
- 2 โค n โค 5 ร 104
- connections.length == n - 1
- connections[i].length == 2
- 0 โค ai, bi โค n - 1
- ai โ bi
- The graph forms a tree structure (connected and acyclic)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code