Skip to content
BytePatterns

Fewest Roads to Link Every Town

HardGraphs#strongly-connected-components#directed-graph~45m

Problem

There are n towns, numbered 0 to n - 1, joined by one-way roads given as pairs (from, to). You may build new one-way roads between any two towns. Return the fewest new roads needed so that every town can reach every other town.

Examples

Input:  n = 5, roads = [(0, 1), (1, 2), (2, 0), (3, 2), (3, 4)]
Output: 2
Why:    0, 1, 2 already form a loop; 3 has no way in, and both the loop
        and 4 have no way out, so two roads are needed, e.g. 2 -> 3 and 4 -> 3
Input:  n = 3, roads = [(0, 1), (1, 2), (2, 0)]
Output: 0
Why:    the three roads already form one loop through every town
Input:  n = 3, roads = []
Output: 3
Why:    edge case, no roads at all: a loop of three new roads is the cheapest fix

Hints

0 / 3

Stuck on the idea rather than the code? Strongly Connected Parts covers it.