#461 · Graphs · Expert · 230 XP · about 45 min
A small web has n pages, numbered 0 to n - 1, and links lists one-way links [a, b] from page a to page b. Two pages belong to the same group when you can get from each of them to the other by following links. Every page is in exactly one group, and a page that cannot get back to itself from any page it links to forms a group on its own.
Write strong_components(n, links) that returns all the groups, each as a sorted list of pages, with the groups sorted by their smallest page.
strong_components(5, [[0, 1], [1, 2], [2, 0], [2, 3], [3, 4]]) # returns [[0, 1, 2], [3], [4]] strong_components(4, [[0, 1], [1, 0], [2, 3], [3, 2], [1, 2]]) # returns [[0, 1], [2, 3]] strong_components(3, []) # returns [[0], [1], [2]]
In the first web, pages 0, 1 and 2 link round in a circle. Page 3 can be reached from them, but no link leads back, so it is a group of its own, and so is page 4.
1 <= n <= 20,000, with up to 50,000 links. A link can be repeated, and a page can link to itself.First solves only, ranked by stars and then time.