progress

~/problems / Graphs / DFS and connected components

Everything reachable from a node

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

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; edges holds 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.

Topic: DFS and connected components. Iterative DFS / flood fill; count and label components.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc