DATA STRUCTURES PROGRAM • GRAPHS

Detect an Undirected Graph Cycle with DFS

Learn how to detect an undirected graph cycle with dfs using a clear C program.

IntermediateCycle detectionParent vertexDFS

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Cycle detected.

COMPLETE C PROGRAM

Complete C implementation

dsa-undirected-cycle-dfs.c
Open in compiler
#include <stdio.h>

int has_cycle(int vertex, int parent, int graph[4][4], int visited[4])
{
    visited[vertex] = 1;
    for (int neighbour = 0; neighbour < 4; neighbour++) if (graph[vertex][neighbour]) {
        if (!visited[neighbour]) {
            if (has_cycle(neighbour, vertex, graph, visited)) return 1;
        } else if (neighbour != parent) return 1;
    }
    return 0;
}

int main(void)
{
    int graph[4][4] = {
        {0,1,1,0}, {1,0,1,0}, {1,1,0,1}, {0,0,1,0}
    };
    int visited[4] = {0};
    puts(has_cycle(0, -1, graph, visited) ? "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. A visited neighbour other than the DFS parent closes an undirected cycle.
  3. Display the computed result.

A visited neighbour other than the DFS parent closes an undirected cycle.

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.