Detect Cycle in Directed Graph

00:00
MediumGraphDFSCycle DetectionColoring
AmazonMicrosoft

Detect if a directed graph has a cycle using DFS and coloring (white=0, gray=1, black=2).

Examples

Input → 0
Output → 1→2→0
Note: cycle → True
Input → 0
Output → 1→2, 0→2
Note: no cycle → False
Input → single vertex self-loop 0
Output → 0 → True