forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycle_detection.py
More file actions
73 lines (56 loc) · 1.79 KB
/
cycle_detection.py
File metadata and controls
73 lines (56 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Cycle Detection in a Directed Graph
Uses DFS with three-colour marking to determine whether a directed graph
contains a cycle.
Reference: https://en.wikipedia.org/wiki/Cycle_(graph_theory)
Complexity:
Time: O(V + E)
Space: O(V)
"""
from __future__ import annotations
from enum import Enum
class TraversalState(Enum):
"""Vertex states during DFS traversal."""
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(
graph: dict[str, list[str]],
traversal_states: dict[str, TraversalState],
vertex: str,
) -> bool:
"""Return True if *vertex* is part of a cycle.
Args:
graph: Adjacency list of a directed graph.
traversal_states: Current DFS colour for each vertex.
vertex: Vertex to inspect.
Returns:
True if a cycle is detected through *vertex*.
"""
if traversal_states[vertex] == TraversalState.GRAY:
return True
traversal_states[vertex] = TraversalState.GRAY
for neighbor in graph[vertex]:
if is_in_cycle(graph, traversal_states, neighbor):
return True
traversal_states[vertex] = TraversalState.BLACK
return False
def contains_cycle(graph: dict[str, list[str]]) -> bool:
"""Return True if *graph* contains at least one cycle.
Args:
graph: Directed graph as ``{vertex: [neighbours], ...}``.
Returns:
True when a cycle exists.
Examples:
>>> contains_cycle({'A': ['B'], 'B': ['A']})
True
>>> contains_cycle({'A': ['B'], 'B': []})
False
"""
traversal_states = {vertex: TraversalState.WHITE for vertex in graph}
for vertex, state in traversal_states.items():
if state == TraversalState.WHITE and is_in_cycle(
graph, traversal_states, vertex
):
return True
return False