Online store~45 min2s · 256 MBtarget O(n + m) time, O(n + m) spacedfs · traversal
An online shop moves stock between n warehouses over two-way lanes. Two warehouses may share more than one lane, and a lane never joins a warehouse to itself. The network is connected: every warehouse can reach every other.
A lane is fragile when its failure splits the warehouses into two groups that cannot reach each other. The shop wants a network with no fragile lane, and it can build new lanes between any two warehouses. What is the fewest new lanes it needs?
Write lanes_to_add(n, lanes).
n warehouses, numbered from 0 to n - 1, and the network is connected.lanes[i] is [a, b]: a two-way lane between warehouses a and b. The same pair may appear more than once, and a differs from b.Input: n = 9, lanes = [[0,1],[1,2],[2,0],[2,3],[3,8],[0,4],[4,5],[5,6],[6,4],[1,7]]
Output: 2Warehouses 0, 1 and 2 form a ring, and so do warehouses 4, 5 and 6. Four lanes are fragile: 2-3, 3-8, 0-4 and 1-7. Removing them leaves five groups: the ring {0, 1, 2}, the single warehouses {3}, {7} and {8}, and the ring {4, 5, 6}.
The solution finds the fragile lanes (bridges) with one depth-first walk. The fragile lanes join the five groups into a tree. A group that only one fragile lane touches is a leaf, and every leaf needs a new lane to reach it from somewhere else.
| Group | Warehouses | Fragile lanes touching it |
|---|---|---|
| 0 | 0, 1, 2 | 3 (lanes 2-3, 0-4, 1-7) |
| 1 | 3 | 2 (lanes 2-3, 3-8) |
| 2 | 4, 5, 6 | 1 (lane 0-4) |
| 3 | 7 | 1 (lane 1-7) |
| 4 | 8 | 1 (lane 3-8) |
Groups 2, 3 and 4 are leaves, so there are 3 leaves. One new lane can cover two leaves, so the answer is 3 halved and rounded up, which is 2. For example, add lanes 4-7 and 8-0.
Input: n = 2, lanes = [[0,1]]
Output: 1The only lane is fragile. A second lane between the same two warehouses fixes it.
Input: n = 4, lanes = [[0,1],[1,2],[2,3],[3,0]]
Output: 0A ring has no fragile lane.
1 ≤ n ≤ 100,0000 ≤ lanes.length ≤ 200,000, and each lane is [a, b] with 0 ≤ a, b < n and a ≠ blanes.length ≥ n - 1Trying every set of new lanes is far beyond reach: for 100,000 warehouses there are about 5 × 10^9 pairs. One depth-first walk finds the fragile lanes in about 6 × 10^5 steps, and counting leaves of the tree of groups is linear.