-
-
Save JamesJi9277/874eb933028d3a557f9b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
假设给你了两个list,一个list是node,一个list是edge | |
假设图中允许单个node的存在 | |
public class Solution { | |
public boolean hasCycle(ArrayList<Node> nodes, ArrayList<Edge> edges) { | |
for(Node node : nodes) { | |
if(detect(node : edges)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
private boolean detect(Node node, ArrayList<Edge> edges) { | |
HashSet<Node> set = new HashSet<Node>(); | |
if(set.contains(node)) { | |
return true; | |
} | |
boolean res = false; | |
for(Edge edge: edges) { | |
if(edge.start == node && !set.contains(edge.end)) { | |
set.add(edge.start); | |
set.add(edge.end); | |
res = res || detect(edge.end, edges); | |
set.remove(edge.end); | |
} | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment