#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_NODES 100
// Graph represented as adjacency list
typedef struct Node {
int vertex;
struct Node* next;
} Node;
Node* graph[MAX_NODES];
bool visited[MAX_NODES];
Node* createNode(int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
void addEdge(int src, int dest) {
Node* newNode = createNode(dest);
newNode->next = graph[src];
graph[src] = newNode;
newNode = createNode(src);
newNode->next = graph[dest];
graph[dest] = newNode;
}
bool dfs(int vertex, int parent) {
visited[vertex] = true; // mark current node visited
Node* temp = graph[vertex];
while (temp != NULL) {
int adjVertex = temp->vertex;
if (!visited[adjVertex]) {
if (dfs(adjVertex, vertex)) {
return true; // cycle found in deeper call
}
} else if (adjVertex != parent) {
return true; // visited node not parent means cycle
}
temp = temp->next; // move to next neighbor
}
return false; // no cycle found from this path
}
bool isCycle(int n) {
for (int i = 0; i < n; i++) {
visited[i] = false; // reset visited
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
if (dfs(i, -1)) {
return true; // cycle detected
}
}
}
return false; // no cycle in any component
}
int main() {
int n = 5; // number of nodes
for (int i = 0; i < n; i++) {
graph[i] = NULL;
}
addEdge(0, 1);
addEdge(1, 2);
addEdge(2, 3);
addEdge(3, 4);
addEdge(4, 0); // adding edge to form cycle
if (isCycle(n)) {
printf("Cycle detected in the graph\n");
} else {
printf("No cycle detected in the graph\n");
}
return 0;
}
visited[vertex] = true; // mark current node visited
mark current node as visited to track traversal
if (!visited[adjVertex]) { if (dfs(adjVertex, vertex)) { return true; } }
visit unvisited neighbor recursively to detect cycle
else if (adjVertex != parent) { return true; }
detect back edge to visited node not parent means cycle
for (int i = 0; i < n; i++) { if (!visited[i]) { if (dfs(i, -1)) { return true; } } }
check all graph components for cycles
Cycle detected in the graph