Reorder Routes to Make All Paths Lead to the City Zero - Problem

There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network forms a tree).

Last year, the ministry of transport decided to orient the roads in one direction because they are too narrow.

Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.

This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

Your task consists of reorienting some roads such that each city can visit city 0. Return the minimum number of edges changed.

It's guaranteed that each city can reach city 0 after reorder.

Input & Output

Example 1 — Basic Tree
$ Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
💡 Note: Start DFS from city 0. Need to reverse edges 1→3, 2→3, and 4→5 so all cities can reach city 0. Edges 0→1 and 4→0 are already pointing toward city 0.
Example 2 — Linear Chain
$ Input: n = 4, connections = [[1,0],[1,2],[3,2]]
Output: 2
💡 Note: Start from city 0. Edge 1→0 is correct (points to 0). Need to reverse 1→2 and 3→2 so cities 2 and 3 can reach city 0 through city 1.
Example 3 — Minimum Case
$ Input: n = 2, connections = [[1,0]]
Output: 0
💡 Note: Only one edge 1→0, which already points toward city 0. No reversals needed.

Constraints

  • 2 ≤ n ≤ 5 × 104
  • connections.length == n - 1
  • connections[i].length == 2
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi

Visualization

Tap to expand
Reorder Routes to City Zero INPUT Original Directed Graph (Tree) 0 1 4 3 2 5 1 --> 3 --> 3 --> 0 --> 5 --> Away from 0 Toward 0 n=6, connections= [[0,1],[1,3],[2,3],[4,0],[4,5]] ALGORITHM - DFS 1 Build Undirected Graph Track original direction 2 Start DFS from Node 0 Visit all connected cities 3 Check Edge Direction If away from 0: count++ 4 Return Total Count Edges to reverse DFS Traversal from 0: Visit 0 0-->1 (reverse) count=1 1-->3 (reverse) count=2 2-->3 (OK) count=2 4-->0 (OK) count=2 4-->5 (reverse) count=3 FINAL RESULT Reoriented Graph (All to 0) 0 1 4 3 2 5 0 (reversed) --> 1 (reversed) --> 3 --> 0 --> 4 (reversed) --> R R R Output: 3 edges reversed All cities can reach 0! Key Insight: Using DFS from node 0, we traverse the tree treating edges as undirected. For each edge, if its original direction points AWAY from node 0 (toward a child), it must be reversed. Edges already pointing toward 0 (from child to parent in DFS) need no change. Count = 3. TutorialsPoint - Reorder Routes to Make All Paths Lead to the City Zero | DFS Traversal Approach
Asked in
Amazon 35 Microsoft 28 Google 22
89.2K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen