DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS
Detect an Undirected Graph Cycle with DSU
Learn how to detect an undirected graph cycle with dsu using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Cycle detected.
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
struct Edge { int source; int destination; };
int find(int parent[], int value)
{
while (parent[value] != value) value = parent[value];
return value;
}
int main(void)
{
struct Edge edges[] = {{0, 1}, {1, 2}, {2, 0}};
int parent[] = {0, 1, 2}, cycle = 0;
for (int index = 0; index < 3; index++) {
int first = find(parent, edges[index].source);
int second = find(parent, edges[index].destination);
if (first == second) { cycle = 1; break; }
parent[second] = first;
}
puts(cycle ? "Cycle detected." : "No cycle.");
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Cycle detected.
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- An edge forms a cycle when both endpoints already share the same representative.
- Display the computed result.
An edge forms a cycle when both endpoints already share the same representative.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
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.
