[prev] 28 [next]

Exercise #6: Buggy Cycle Check

A graph has a cycle if
  • it has a path of length > 1
  • with start vertex src = end vertex dest
  • and without using any edge more than once
We are not required to give the path, just indicate its presence.

The following DFS cycle check has two bugs. Find them.

hasCycle(G):
|  Input  graph G
|  Output true if G has a cycle, false otherwise
|
|  choose any vertex v∈G
|  return dfsCycleCheck(G,v)

dfsCycleCheck(G,v):
|  mark v as visited
|  for each (v,w)∈edges(G) do
|  |  if w has been visited then   // found cycle
|  |     return true
|  |  else if dfsCycleCheck(G,w) then
|  |     return true
|  end for
|  return false                    // no cycle at v