Cycle Detection in Graphs in C

Advanced
8 min read
Updated: Nov 2026
2 examples

Finding Cycles with DFS

In an undirected graph a DFS finds a cycle when it meets an already visited vertex that is not its parent. In a directed graph that is not enough; use three states: unvisited, in progress (on the current DFS path), and done. Meeting an in-progress vertex means a back edge, which means a cycle.

Remember
undirected: visited neighbor != parent  => cycle
directed  : neighbor is "in progress"    => cycle

Cheat Sheet

Keep these facts handy while you work with Cycle Detection in Graphs in C in C.

TopicDetail
UndirectedTrack parent
DirectedThree states
TimeO(V + E)
DAGA directed graph with no cycles

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Topological Sorting in C.

Example 1 — Undirected graphs

A triangle has a cycle; a path does not.

C
#include <stdio.h>
#define V 4

static int adj[V][V], visited[V];

static int dfs(int u, int parent) {
    visited[u] = 1;
    for (int v = 0; v < V; v++) {
        if (!adj[u][v]) continue;
        if (!visited[v]) { if (dfs(v, u)) return 1; }
        else if (v != parent) return 1;
    }
    return 0;
}

static int has_cycle(int edges[][2], int m) {
    for (int i = 0; i < V; i++) {
        visited[i] = 0;
        for (int j = 0; j < V; j++) adj[i][j] = 0;
    }
    for (int i = 0; i < m; i++) {
        adj[edges[i][0]][edges[i][1]] = 1;
        adj[edges[i][1]][edges[i][0]] = 1;
    }
    for (int v = 0; v < V; v++)
        if (!visited[v] && dfs(v, -1)) return 1;
    return 0;
}

int main(void) {
    int triangle[][2] = {{0, 1}, {1, 2}, {2, 0}};
    int path[][2] = {{0, 1}, {1, 2}, {2, 3}};
    printf("triangle: %s\n", has_cycle(triangle, 3) ? "cycle" : "no cycle");
    printf("path: %s\n", has_cycle(path, 3) ? "cycle" : "no cycle");
    return 0;
}

How It Works

  1. In the triangle, DFS from 2 sees 0, which is visited and is not 2's parent (1).
  2. In the path every visited neighbor is just the parent.
  3. The parent argument prevents the edge you came from being mistaken for a cycle.

Example 2 — Directed graphs

A directed triangle versus a DAG.

C
#include <stdio.h>
#define V 3

static int adj[V][V], state[V];

static int dfs(int u) {
    state[u] = 1;
    for (int v = 0; v < V; v++) {
        if (!adj[u][v]) continue;
        if (state[v] == 1) return 1;
        if (state[v] == 0 && dfs(v)) return 1;
    }
    state[u] = 2;
    return 0;
}

static int has_cycle(int edges[][2], int m) {
    for (int i = 0; i < V; i++) {
        state[i] = 0;
        for (int j = 0; j < V; j++) adj[i][j] = 0;
    }
    for (int i = 0; i < m; i++) adj[edges[i][0]][edges[i][1]] = 1;
    for (int v = 0; v < V; v++)
        if (state[v] == 0 && dfs(v)) return 1;
    return 0;
}

int main(void) {
    int ring[][2] = {{0, 1}, {1, 2}, {2, 0}};
    int dag[][2] = {{0, 1}, {0, 2}, {1, 2}};
    printf("0->1->2->0: %s\n", has_cycle(ring, 3) ? "cycle" : "no cycle");
    printf("DAG: %s\n", has_cycle(dag, 3) ? "cycle" : "no cycle");
    return 0;
}

How It Works

  1. In the ring, DFS reaches 2 and finds an edge back to 0, which is still in progress (state 1).
  2. In the DAG, 2 is reached twice but is already finished (state 2), which is not a cycle.
  3. Two states are not enough for directed graphs: "visited" and "on the current path" are different things.

Edge Cases & Pitfalls

Check these before relying on Cycle Detection in Graphs in C in real programs.

multi

Parallel edges

Two edges between the same pair form a cycle that a simple matrix cannot represent.

dir

Using undirected logic on digraphs

A diamond-shaped DAG would be falsely reported as cyclic.

Key Takeaways

  • Undirected: visited and not parent.
  • Directed: in-progress state.
  • O(V + E).

One line: In an undirected graph a DFS finds a cycle when it meets an already visited vertex that is not its parent.

Frequently Asked Questions

Run DFS with three states and report a cycle if you reach a vertex that is still in progress.
Run DFS and report a cycle if you find a visited neighbor that is not the vertex you came from.
Continue with "Topological Sorting in C" next. Order a DAG with Kahn's algorithm and detect cycles by counting. The C Graph Algorithms hub lists every topic in order.

Next: Topological Sorting in C

Order a DAG with Kahn's algorithm and detect cycles by counting.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful