Skip to content
BytePatterns

Mutual Reach Groups

HardGraphs#strongly-connected-components#dfs~45m

Problem

A directed graph has n nodes numbered from 0 and a list of one-way edges (u, v). Split the nodes into groups so that two nodes share a group exactly when each can reach the other by following edges. Return the groups, each sorted ascending, with the list of groups sorted as well. A node that reaches nobody and is reached by nobody still forms a group of its own.

Examples

Input:  n = 5, edges = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4)]
Output: [[0, 1, 2], [3], [4]]
Why:    0, 1 and 2 form a loop; 3 and 4 can never get back
Input:  n = 4, edges = [(0, 1), (1, 0), (2, 3), (3, 2), (1, 2)]
Output: [[0, 1], [2, 3]]
Why:    the edge 1 -> 2 runs one way only, so the pairs stay apart
Input:  n = 1, edges = []
Output: [[0]]
Why:    edge case, a lone node is its own group

Hints

0 / 3

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