CSES - Cycles

Your task is to design a class that supports adding an edge to a directed graph and finding if the graph contains a directed cycle.

You may assume that the number of vertices is at most 50 and that the methods of the class are called at most 100 times.

In a file cycles.py, implement a class Cycles with the following methods:

  • constructor with the number of vertices as a parameter
  • add_edge adds an edge from a vertex a to a vertex b
  • check reports if the graph has a directed cycle
class Cycles:
    def __init__(self,n):
        # TODO

    def add_edge(self,a,b):
        # TODO

    def check(self):
        # TODO

if __name__ == "__main__":
    c = Cycles(4)
    c.add_edge(1,2)
    c.add_edge(2,3)
    c.add_edge(1,3)
    c.add_edge(3,4)
    print(c.check()) # False
    c.add_edge(4,2)
    print(c.check()) # True