Implement a Graph With Path and Cycle Detection
Problem
Implement a directed graph supporting addNode, removeNode, addEdge, removeEdge, hasPath(a, b), and hasCycle().
Input / Output
- Input: a sequence of mutation and query calls.
- Output:
hasPath(a,b)returns whether b is reachable from a;hasCycle()returns whether the graph has any directed cycle.
Constraints
- Directed graph; handle removal of nodes that still have incident edges.
Example
addEdge(A,B); addEdge(B,C); hasPath(A,C) -> true; addEdge(C,A); hasCycle() -> true.
added …