← 返回 sofi 的题目列表Reachable Nodes in a Directed Graph
类型:qbank
Given a directed graph represented by vertices and their neighbor lists, implement `reachableNodes(Vertex start)` to return every vertex reachable from the starting vertex. The follow-up compares DFS and BFS memory behavior, including recursive-stack overflow on a graph with depth around 1,000.
Requirements
Implement Collection<Vertex> reachableNodes(Vertex start) for a directed graph whose vertices expose their outgoing neighbors.
Return the set of vertices reachable from start, including start itself.
Handle cycles without revisiting vertices indefinitely.
Be prepared to implement either recursive DFS or an iterative traversal using an explicit stack.
Follow-up: compare DFS and BFS, including their memory usage and behavior on deep versus wide graphs.
Examples
Given the adjacency lists:
A: [B]
B: [C, D]
D: [E]
E: [B]
Starting from A must terminate despite the B -> D -> E -> B cycle and return all reachable vertices.
Notes
A visited set is required for cycle handling and uses O(V) space.
Recursive DFS uses call-stack space proportional to graph depth and may overflow on a sufficiently deep chain; depth 1,000 was raised explicitly.
Iterative DFS replaces the call stack with an explicit stack.
BFS stores the current frontier in a queue, so its peak auxiliary memory depends on graph width. It also discovers shortest paths in an unweighted graph, whereas DFS does not.