Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Created April 6, 2020 02:19
Show Gist options
  • Select an option

  • Save nhudinhtuan/d4f9b0d20998b09c9f4d12384a20045d to your computer and use it in GitHub Desktop.

Select an option

Save nhudinhtuan/d4f9b0d20998b09c9f4d12384a20045d to your computer and use it in GitHub Desktop.

Revisions

  1. nhudinhtuan created this gist Apr 6, 2020.
    35 changes: 35 additions & 0 deletions is_cyclic_directed_graph.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    # graph is represented by adjacency list: List[List[int]]
    # DFS to detect cyclic
    def is_cyclic_directed_graph(graph):
    # set is used to mark visited vertices
    visited = set()
    # set is used to keep track the ancestor vertices in recursive stack.
    ancestors = set()

    def is_cyclic_recur(current_vertex):
    # mark it visited
    visited.add(current_vertex)
    # add it to ancestor vertices
    ancestors.add(current_vertex)

    # Recur for all the vertices adjacent to current_vertex
    for v in graph[current_vertex]:
    # If the vertex is not visited then recurse on it
    if v not in visited:
    if is_cyclic_recur(v):
    return True
    elif v in ancestors:
    # found a back edge, so there is a cycle
    return True

    # remove from the ancestor vertices
    ancestors.remove(current_vertex)
    return False

    # call recur for all vertices
    for u in range(len(graph)):
    # Don't recur for u if it is already visited
    if u not in visited:
    if is_cyclic_recur(u):
    return True
    return False