#K48212. Cycle Detection in Directed Graphs

    ID: 28371 Type: Default 1000ms 256MiB

Cycle Detection in Directed Graphs

Cycle Detection in Directed Graphs

You are given a directed graph with \( n \) nodes numbered from 0 to \( n-1 \) and \( m \) edges. Your task is to determine whether the graph contains at least one cycle.

A cycle exists if there is a non-empty path from a node back to itself following the directed edges. The input graph may be disconnected or may contain self-loops.

Note: A self-loop (an edge from a node to itself) is considered a cycle. Use appropriate algorithms such as Depth First Search (DFS) to detect cycles.

inputFormat

The input is read from stdin and has the following format:

n m
u1 v1
u2 v2
... 
um vm

Where:

  • n is the number of nodes.
  • m is the number of directed edges.
  • Each of the next m lines contains two integers u and v representing a directed edge from node u to node v.

outputFormat

Output a single line to stdout containing either True if the graph contains at least one cycle, or False if it does not.

## sample
4 4
0 1
1 2
2 3
3 1
True