Back to course home
0% completed
Vote For New Content
Reorder Routes to Make All Paths Lead to the City Zero (medium)
Problem Statement
You are given n
cities labeled from 0
to n-1
and n-1
roads, which form a tree structure. Each road is directed, meaning it has a specific direction.
These roads are represented by the array connections
, where connections[i] = [a, b]
indicates a road from city a
to city b
.
Change the direction of some roads so that every city can reach city 0
.
Return the minimum number of edges that need to be reversed.
Examples
Example 1
- Input: n = 5, connections = [[0, 1], [1, 2], [2, 3], [4, 3]]
- Expected Output: 3
- Justification: To make all cities lead to city
0
, reverse the roads[0, 1]
,[1, 2]
and[2, 3]
. This will make the paths0 <- 1 <- 2 <- 3 <- 4
.
Example 2
- Input: n = 6, connections = [[0, 1], [2, 0], [3, 2], [4, 3], [5, 3
- Expected Output: 1
- Justification: To make all cities lead to city
0
, reverse the road[0, 1]
.
Example 3
- Input: n = 4, connections = [[1, 0], [2, 1], [3, 2]]
- Expected Output: 0
- Justification: All cities have path from itself to 0. So, we don't need to reverse any edge.
Constraints:
- 2 <= n <= 5 * 10<sup>4<sup>
- connections.length == n - 1
- connections[i].length == 2
- 0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1
- a<sub>i</sub> != b<sub>i</sub>
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Like the course? Get enrolled and start learning!
On this page
Problem Statement
Examples
Try it yourself