Given an undirected graph and a starting node, return how many nodes are reachable from the start, including the start itself.
rareRouting(graph, start)
Input format: edges | start, edges as a,b pairs.
edges a,b b,c d,e, start a // → 3 (a, b, c)
edges a,b b,c d,e, start d // → 2 (d, e)
edges (none), start a // → 1
"How many nodes can I reach from here" asks for the size of the start's connected component — every node joined to it by some chain of edges. No weighting or shortest-path concern, just reachability, so BFS or DFS work equally well.
The graph can contain cycles, so a naive traversal revisiting nodes could loop forever or waste work. Maintain a visited set: arriving at a node, check it first. Already visited means stop; otherwise mark it visited and continue to its neighbors.
DFS falls out of recursion naturally: visit, mark, recurse into each neighbor. BFS uses a queue instead, processing in waves. Both visit the same set of nodes — the order differs, the count doesn't.
An isolated start still counts as 1 — it reaches itself trivially, which is why marking the start visited happens before looking at any neighbors. Nodes in other components are never visited and correctly excluded, since reachability respects component boundaries.
def rare_routing(graph, start):
visited = set()
def dfs(node):
if node in visited:
return
visited.add(node)
for nxt in graph.get(node, []):
dfs(nxt)
dfs(start)
return len(visited)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.