DATA STRUCTURES PROGRAM • GRAPHS

Detect a Directed Graph Cycle with DFS Colors

Learn how to detect a directed graph cycle with dfs colors using a clear C program.

IntermediateDirected cycleDFS colorsRecursion stack

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Cycle detected.

COMPLETE C PROGRAM

Complete C implementation

dsa-directed-cycle-colors.c
Open in compiler
#include <stdio.h>

int directed_cycle(int vertex, int graph[4][4], int color[4])
{
    color[vertex] = 1;
    for (int neighbour = 0; neighbour < 4; neighbour++) if (graph[vertex][neighbour]) {
        if (color[neighbour] == 1) return 1;
        if (color[neighbour] == 0 && directed_cycle(neighbour, graph, color)) return 1;
    }
    color[vertex] = 2;
    return 0;
}

int main(void)
{
    int graph[4][4] = {
        {0,1,0,0}, {0,0,1,0}, {1,0,0,1}, {0,0,0,0}
    };
    int color[4] = {0}, cycle = 0;
    for (int vertex = 0; vertex < 4 && !cycle; vertex++)
        if (color[vertex] == 0) cycle = directed_cycle(vertex, graph, color);
    puts(cycle ? "Cycle detected." : "No cycle.");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Cycle detected.
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. An edge to a currently active gray vertex is a directed back edge.
  3. Display the computed result.

An edge to a currently active gray vertex is a directed back edge.

EFFICIENCY

Time and space complexity

Time complexity

O(V²) with matrix

Auxiliary space

O(V)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.