Reorder Routes to Make All Paths Lead to the City Zero

You are given a directed graph of roads between cities. Return the minimum number of roads that must be reversed so every city can reach city 0. Pattern focus: Directed vs Undirected. The core challenge is that road direction matters, unlike in an undirected graph.

Input Format

n = number of cities, connections = directed roads

Output Format

minimum number of edge reversals needed

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9
  • n, connections must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

n = 6
connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]

Output:

3

Explanation:

Three roads must be reversed so every city can reach 0.

Example 2:

Input:

n = 3
connections = [[1,0],[2,0]]

Output:

0

Explanation:

All cities already have a path to city 0.

Loading...
Reorder Routes to Make All Paths Lead to the…