Amazon Interview Question
Software Engineer / DevelopersAs per http://pages.cs.wisc.edu/~vernon/cs367/notes/13.GRAPH.html, here's the code for cycle detection::
{{
static boolean hasCycle(Graphnode n) {
n.setMark( grey );
Iterator it = n.getSuccessors().iterator();
while(it.hasNext()) {
Graphnode m = it.next();
if (m.getMark() == grey) return true;
if (m.getMark() != black) {
if (hasCycle(m)) return true;
}
}
n.setMark( black);
return false;
}
}}
To detect cycles in a directed graph, the most common technique is to perform a depth first search (DFS) of the graph. According to the standard algorithm, we mark each node as white initially, grey when it is visited during search, and black when all its neighbours are finished. During the search, whenever we encounter a node thats already marked grey, we know thats a cycle.
- Anonymous August 06, 2009The logic is simple. Any node in the cycle will again be visited when its descendent's neighbours are being seached recursively, before all the descendents are finished.
The run time is the same as DFS, O(|V| + |E|).