All problems
0986MediumDepth-First SearchBreadth-First SearchGraph Theory

Roads to Turn Round for the Depot

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1466Reorder Routes to Make All Paths Lead to the City Zero

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A region has n towns numbered from zero, joined by n - 1 one-way roads listed in connections, each [from, to]. Ignoring the directions, the roads join every town to every other with no loops.

Return the fewest roads that must be turned round so that every town can reach town 0 by following the roads the way they point.

Examples

Example 1

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

Sweeping outwards from town 0, the roads to 1, to 3 and to 5 all point away from it and must be turned; the roads from 2 and from 4 already point the right way.

Example 2

Input
n = 4, connections = [[3, 2], [2, 1], [1, 0]]
Output
0

The towns run in a line and every road already points towards town 0.

Example 3

Input
n = 4, connections = [[0, 1], [1, 2], [2, 3]]
Output
3

The towns run in a line and every road points away from town 0, so all three must be turned.

Constraints

  • 2 <= n <= 5 * 10^4
  • connections.length == n - 1
  • connections[i].length == 2
  • 0 <= connections[i][0] <= n - 1
  • 0 <= connections[i][1] <= n - 1
  • The two towns on a road are different
  • Ignoring directions, the roads join every town with no loops

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def min_reorder(n: int, connections: list[list[int]]) -> int:
Java
public int minReorder(int n, int[][] connections)
September 7
Apply