Reorder Routes to Make All Paths Lead to the City Zero
Reorder Routes to Make All Paths Lead to the City Zero
There are n cities numbered from 0 to n - 1. The cities are connected by n - 1 roads, forming a tree structure where there is exactly one path between any two distinct cities. Last year, the ministry of transport decided to orient all roads in one direction.
Roads are given as a list of connections, where connections[i] = [ai, bi] represents a road directed from city ai to city bi.
This year, city 0 is the capital, and many people want to travel to it. Your task is to reorient the minimum number of roads such that every city can reach city 0. It is guaranteed that after reorienting some roads, each city can reach city 0.
Example 1:
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] Output: 3 Explanation: Change the direction of edges shown in red such that each node can reach 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 shown in red such that each node can reach node 0 (capital).
Constraints:
2 <= n <= 5 * 10^4connections.length == n - 1connections[i].length == 20 <= ai, bi <= n - 1ai != bi
Similar LeetCode problem: Reorder Routes to Make All Paths Lead to the City Zero
AI interview prep
Core dilemma
Minimizing edge reorientations in a tree to achieve a specific connectivity target (all nodes reaching node 0) while respecting original road directions.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Reorder Routes to Make All Paths Lead to the City Zero
Reorder Routes to Make All Paths Lead to the City Zero
There are n cities numbered from 0 to n - 1. The cities are connected by n - 1 roads, forming a tree structure where there is exactly one path between any two distinct cities. Last year, the ministry of transport decided to orient all roads in one direction.
Roads are given as a list of connections, where connections[i] = [ai, bi] represents a road directed from city ai to city bi.
This year, city 0 is the capital, and many people want to travel to it. Your task is to reorient the minimum number of roads such that every city can reach city 0. It is guaranteed that after reorienting some roads, each city can reach city 0.
Example 1:
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] Output: 3 Explanation: Change the direction of edges shown in red such that each node can reach 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 shown in red such that each node can reach node 0 (capital).
Constraints:
2 <= n <= 5 * 10^4connections.length == n - 1connections[i].length == 20 <= ai, bi <= n - 1ai != bi
Similar LeetCode problem: Reorder Routes to Make All Paths Lead to the City Zero