[Python] How to detect a cycle in a directed graph with Python?

Discussão em 'Python' iniciado por Stack, Julho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have some input like: [('A', 'B'),('C', 'D'),('D', 'C'),('C', 'D')]. I want to look for if the existence of a cycle in a directed graph represented by this edgeList.

    I read a discussion: https://www.geeksforgeeks.org/detect-cycle-in-a-graph/, however it has some errors when the case is:

    g = Graph(3)
    g.addEdge('A', 'B')
    g.addEdge('B', 'C')
    g.addEdge('C', 'A')


    Its result is 'Graph has no cycle'. This is clearly wrong. Can you help me to solve this problem?

    Continue reading...

Compartilhe esta Página