given a directed graph check whether it contains a cycle reallife scenario deadlock detection in a system processes may be represented by vertices then and an edge a b could mean that process a is waiting for b to release its lock on a resource for a given node white has not been visited yet gray is currently being investigated for a cycle black is not part of a cycle determines if the given vertex is in a cycle param traversalstates for each vertex the state it is in determines if there is a cycle in the given graph the graph should be given as a dictionary graph a b c b d c f d e f e b f for a given node white has not been visited yet gray is currently being investigated for a cycle black is not part of a cycle determines if the given vertex is in a cycle param traversal_states for each vertex the state it is in determines if there is a cycle in the given graph the graph should be given as a dictionary graph a b c b d c f d e f e b f
from enum import Enum


class TraversalState(Enum):
    
    WHITE = 0
    GRAY = 1
    BLACK = 2

def is_in_cycle(graph, traversal_states, 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):
    
    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