Reorder Routes to Make All Paths Lead to the City Zero

There are `n` cities numbered `0` to `n - 1` and `n - 1` one-way roads, so that there is exactly one way to travel between any two cities if road directions are ignored (the roads form a tree). `connections[i] = [a_i, b_i]` is a road from `a_i` to `b_i`. The capital is city 0. Reorient the fewest roads so that every city can reach city 0, and return that number. It is guaranteed that after reordering, every city can reach city 0.

30:00

Reorder Routes to Make All Paths Lead to the City Zero
medium
Free written solution
Topics
Companies

There are n cities numbered 0 to n - 1 and n - 1 one-way roads, so that there is exactly one way to travel between any two cities if road directions are ignored (the roads form a tree). connections[i] = [a_i, b_i] is a road from a_i to b_i. The capital is city 0. Reorient the fewest roads so that every city can reach city 0, and return that number. It is guaranteed that after reordering, every city can reach city 0.

Example 1:
Input: {"n":6,"connections":[[0,1],[1,3],[2,3],[4,0],[4,5]]}
Output: 3
Constraints:
  • 2≤n≤5×1042 \leq n \leq 5 \times 10^4

  • connections.length==n−1\text{connections.length} == n - 1

  • connections[i].length==2\text{connections}[i].\text{length} == 2

  • 0≤ai,bi≤n−10 \leq a_i, b_i \leq n - 1

  • ai≠bia_i \neq b_i

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":6,"connections":[[0,1],[1,3],[2,3],[4,0],[4,5]]}

Store each of the 5 roads in both cities' lists. The owner's direction is tagged 1 (points away from the neighbour) and the reverse direction 0.

visiting

-

reached

1/6

flipped

0

012345
green: already leads to 0red: flippeddashed: not reached

queue

0
Variables
VariableValue
n6
roads5
DepthFunction Call
Stack empty
0/13