
This question is actually asking how to check whether a graph has a cycle:
1. Put all nodes and it's next node into a hashmap. e.g 1 -> [2,3]
2. For each node, perform DFS, recursively check if there's a cycle. Create a state array, 0 = not assigned, 1 = checked, -1 = is checking
3. In each DFS, perform:
i. if the node is check, then it would be a cycle.
ii. if the node is checked, no need to continue.
iii. if the node is not a hashmap key, which means it's the end of the current branch, assign the state to 1, return true;
iv. Assign the node to -1, currently checking.
v. If the node is not assigned, DFS the next node, if any of the step is false, return false.
vi. After check its children, and no false, then there's no cycle, return true.
Code:
