← Back to problems
UNSW COMP2521 · hard

DFS: Detect Cycle (Directed)

DFS: Detect Cycle (Directed)

Given a directed graph, decide whether it contains a cycle.

Color nodes white/gray/black during DFS; an edge to a gray node (a back edge) means there's a cycle.

Input: line 1 V E (vertices 0..V-1, edges); then E lines u v (directed edge u->v). Output: YES or NO.

Example: 3 3 / 0 1 / 1 2 / 2 0 -> YES.