← 返回 sofi 的题目列表Reachable Nodes in a Directed Graph
类型:online_judge
Problem: Reachable Nodes in a Directed Graph
Given a directed graph and a starting node start, return all nodes that are reachable from start.
The graph may contain cycles, for example:
A -> B
B -> C, D
D -> E
E -> B
Starting from A, the reachable nodes are A, B, C, D, E. Since B -> D -> E -> B forms a cycle, your traversal must avoid infinite loops.
Implement a function that returns all reachable nodes. For deterministic judging, output the reachable nodes sorted in lexicographical order.
Input Format
n m
v1 v2 ... vn
u1 v1
u2 v2
...
um vm
start
n is the number of nodes.
m is the number of directed edges.
The second line contains n unique node names.
The next m lines each contain two strings u v, representing a directed edge u -> v.
The last line contains the starting node start.
Output Format
Print all nodes reachable from start, including start itself, sorted in ascending lexicographical order and separated by spaces.
Constraints
1 <= n <= 10^5
0 <= m <= 2 * 10^5
Node names are non-empty strings without spaces.
start is guaranteed to be one of the given nodes.
The graph may be disconnected and may contain self-loops or cycles.
Example
Input:
5 5
A B C D E
A B
B C
B D
D E
E B
A
Output:
A B C D E
Example
Input
5 5
A B C D E
A B
B C
B D
D E
E B
A
Output
A B C D E