Write reachable(n, edges, start) -> set[int]: the set of nodes you can reach from start in an undirected graph, including start. That set is start's connected component.
- Nodes are
0 .. n-1;edgesholds undirected pairs(a, b). Repeats and self-loops may appear. - Build an adjacency list, then walk it with an explicit stack (a Python list), not recursion: one test is a 20,000-node path, past Python's recursion limit of about 1000.
reachable(6, [(0, 1), (1, 2), (3, 4)], 0) # {0, 1, 2}
reachable(6, [(0, 1), (1, 2), (3, 4)], 5) # {5} (no edges at all)
Up to 10**5 nodes and 2 * 10**5 edges.
Show hint
mark a node as seen when you push it, and only push unseen neighbours, so each node is pushed at most once.