题目
http://www.geeksforgeeks.org/detect-cycle-in-a-graph/
思路:DFS + path
Java实现
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
class GraphNode {
private List<GraphNode> children = new ArrayList<GraphNode>();
public List<GraphNode> getChildren() {
return children;
}
public void addChild(GraphNode node) {
children.add(node);
}
}
public class Solution {
public boolean detectCycle(GraphNode node) {
return dfs(node, new HashSet<GraphNode>());
}
private boolean dfs(GraphNode node, HashSet<GraphNode> path) {
if (node == null) {
return false;
} else if (path.contains(node)) {
return true;
}
path.add(node);
for (GraphNode child : node.getChildren()) {
if (dfs(child, path)) {
return true;
}
}
path.remove(node);
return false;
}
public static void main(String[] args) {
GraphNode node1 = new GraphNode();
GraphNode node2 = new GraphNode();
GraphNode node3 = new GraphNode();
Solution sol = new Solution();
node1.addChild(node2);
System.out.println(sol.detectCycle(node1)); // false 1->2
node2.addChild(node3);
System.out.println(sol.detectCycle(node1)); // false 1->2->3
node1.addChild(node3);
System.out.println(sol.detectCycle(node1)); // false
node3.addChild(node1);
System.out.println(sol.detectCycle(node1)); // true
}
}