data-structures · intermediate · ~15 min

Detect a cycle (directed)

Directed cycle detection with DFS colors.

Challenge

int has_cycle_directed(const int *adj,int n);

Return 1 if the directed graph contains a cycle, else 0.

Input format

adj n×n directed 0/1.

Output format

1 if cyclic, else 0.

Constraints

Self-loops count as cycles if present (tests use none).

Starter code

#include <stddef.h>
/* Return 1 if the DIRECTED graph (adjacency matrix) contains a cycle, else 0. */
int has_cycle_directed(const int *adj,int n){ (void)adj;(void)n; return 0; }

Common mistakes

Using undirected logic; a cross-edge to a finished vertex is not a cycle.

Edge cases to handle

DAG → 0; a→b→a → 1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.