I am doing interview studies and can't find a simple DFS for a cycle-finding algorithm. I want someone to tell me if my DFS algorithm works and how it can be improved.
Where can you get a typical DFS cycle finding algorthm for Java? I assume you have to "mark" the nodes and edges in order to find a cycle? Can you simplify / improve it? e.g. A-->B-->A , shouldn't be a cycle!
boolean isCycled(Node root){
return isCycled(root, -1);
}
boolean isCycled(Node n, int edgeNum){
//base case
if(n==null) return false;
//base case: if an unexplored edge that lead to a node that is visited.
if(edgeNum>=0){//make sure it is not the first node
if(n.visted==true && edge[edgeNum]!=true ) {
return true; //found cycle
}
}
n.visited=true;
edge[edgeNum]==true; // already explored edge wont' lead to cycle.
List nodes = getAllNeigbors(n); //visited or unvisited
boolean isCycle = false;
for(Node node : nodes){
isCycle = isCycle || isCycled(node, getEdgeNum(n,node));
}
return isCycle;
}
A -> B -> A
not be a cycle? Can different nodes have the same name? If so, how do you distinguish nodes? – tobias_k Jul 18 '13 at 7:44edge[edgeNum]==true;
compilation error. I think it's a copy-paste typo. – Anirban Nag 'tintinmj' Nov 28 '13 at 10:54