7.2. Cycle Detection
This section describes an algorithm to detect a cycle in a graph.
Last updated
This section describes an algorithm to detect a cycle in a graph.
Last updated
©2023 Emory University - All rights reserved
A cycle in a graph can be detected by traversing through the graph:
Let us define the containsCycle()
method under the Graph
class that returns true if the graph contains any cycle; otherwise, false:
L2
: initially all vertices are not visited.
L4
: iterates until all vertices are visitied:
L5-6
: if the recursive call finds a cycle, returns true
.
What is the worst-case complexity of the
containsCycle()
method?
L2-3
: marks the target vertex visited.
L5
: for each incoming edge of the target vertex:
L6-7
: returns true if the source vertex of this edge has seen before.
L9-10
: returns true if the recursive call finds a cycle.
Why do we need to pass the new
HashSet
for every call inL5
?