Reorder Routes to Make All Paths Lead to the City Zero Problem
Description
LeetCode Problem 1466.
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 form 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] = [a_i, b_i] represents a road from city a_i to city b_i.
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 the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach city 0 after reorder.
Example 1:

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 2:

Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 3:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Constraints:
2 <= n <= 5 * 10^4connections.length == n - 1connections[i].length == 20 <= a_i, b_i <= n - 1a_i != b_i
Solution
Approach: Traverse from City 0 and Count Roads Pointing Away
Ignoring direction, the roads form a tree, so every city has exactly one path to city 0, and each road on that path must point toward 0. Seen from city 0, that means every road must point toward the root. A road that points away from the root has to be flipped, and one that already points toward it must not be, so the answer is the number of roads that point away from city 0.
To find them, store each road in both directions in an adjacency list with a cost: a -> b is stored as (b, 1) at a (going from a to b follows the road, which is away from the root if a is the parent) and (a, 0) at b. Then walk the tree from city 0, and every time we reach a new city, add the cost of the edge we used. Each road is crossed exactly once, from parent to child, so the sum counts exactly the roads that point away from 0.
The tree can be a path of 5 · 104 cities, so the walk uses an explicit stack rather than recursion.
Complexity: O(n) time and O(n) extra space for the adjacency list.
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
# adj[x] holds (y, cost): cost 1 if the road points x -> y, i.e. away from city 0
# once we walk outward from 0, so it has to be flipped.
adj = [[] for _ in range(n)]
for a, b in connections:
adj[a].append((b, 1))
adj[b].append((a, 0))
visited = [False] * n
visited[0] = True
stack = [0]
flips = 0
while stack:
x = stack.pop()
for y, cost in adj[x]:
if not visited[y]:
visited[y] = True
flips += cost
stack.append(y)
return flips