#C148. Cyclic Dependency Checker
Cyclic Dependency Checker
Cyclic Dependency Checker
You are given a directed graph represented as an adjacency list. The graph is provided via standard input. Your task is to determine whether the graph contains a cycle (i.e. a cyclic dependency).
Formally, given a directed graph with n
nodes numbered from 0 to n-1, and m
directed edges, check if there exists a sequence of nodes v0,v1,...,vk such that:
\( v_0 = v_k \) and for every \( 0 \leq i < k,\ v_i \to v_{i+1}\) is a directed edge.
Hint: You may use a Depth First Search (DFS) approach and a recursion stack to detect cycles. In terms of time complexity, if \(n\) is the number of nodes and \(m\) is the number of edges, an optimal DFS solution runs in \(O(n+m)\) time.
inputFormat
The input is given from stdin and is formatted as follows:
- The first line contains two space-separated integers,
n
andm
, wheren
is the number of nodes andm
is the number of edges. - The next
m
lines each contain two space-separated integers,u
andv
, representing a directed edge from nodeu
to nodev
.
Note: Nodes are numbered from 0 to n-1.
outputFormat
Output a single line to stdout containing either true
if the graph contains a cycle, or false
if it does not.
4 6
0 1
0 2
1 2
2 0
2 3
3 3
true