data-structures · intermediate · ~15 min

Detect a cycle (undirected)

Undirected cycle detection via DFS with a parent.

Challenge

For an undirected graph (symmetric adj, no self-loops):

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

Return 1 if it contains a cycle, else 0.

Input format

adj n×n symmetric 0/1.

Output format

1 if cyclic, else 0.

Constraints

Starter code

#include <stddef.h>
/* Return 1 if the UNDIRECTED graph (symmetric adjacency matrix, no self-loops) contains a cycle, else 0. */
int has_cycle_undirected(const int *adj,int n){ (void)adj;(void)n; return 0; }

Common mistakes

Counting the edge back to your parent as a cycle.

Edge cases to handle

A tree/forest → 0; a triangle → 1.

Background lessons

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