def is_cyclic ( graph ) : path = set ( ) def visit ( vertex ) : path . add ( vertex ) for neighbour in graph . get ( vertex , ( ) ) : if neighbour in path or visit ( neighbour ) : return True path . remove ( vertex ) return False return any ( visit ( v ) for v in graph )
python code that sees if a graph has a cycle
Return True if the directed graph g has a cycle . The directed graph should be represented as a dictionary mapping of edges for each node .
def is_cyclic(graph):
    """
    Return True if the directed graph g has a cycle. The directed graph
    should be represented as a dictionary mapping of edges for each node.
    """
    path = set()

    def visit(vertex):
        path.add(vertex)
        for neighbour in graph.get(vertex, ()):
            if neighbour in path or visit(neighbour):
                return True
        path.remove(vertex)
        return False

    return any(visit(v) for v in graph)