#include <stdio.h> #include <stdbool.h> #define V 4 bool dfs(int v, int parent, bool visited[], int graph[V][V]) { visited[v] = true; for (int i = 0; i < V; i++) { if (graph[v][i]) { if (!visited[i]) { if (dfs(i, v, visited, graph)) return true; } else if (i != parent) { return true; } } } return false; } int main() { int graph[V][V] = { {0, 1, 0, 0}, {1, 0, 1, 1}, {0, 1, 0, 1}, {0, 1, 1, 0} }; bool visited[V] = {false}; bool hasCycle = false; for (int i = 0; i < V; i++) { if (!visited[i]) { if (dfs(i, -1, visited, graph)) { hasCycle = true; break; } } } if (hasCycle) { printf("Cycle detected\n"); } else { printf("No cycle detected\n"); } return 0; }
The graph has edges forming a cycle: nodes 1, 2, and 3 form a cycle. The DFS detects this cycle and prints "Cycle detected".
#include <stdio.h> #include <stdbool.h> #define V 3 bool dfs(int v, int parent, bool visited[], int graph[V][V]) { visited[v] = true; for (int i = 0; i < V; i++) { if (graph[v][i]) { if (!visited[i]) { if (dfs(i, v, visited, graph)) return true; } else if (i != parent) { return true; } } } return false; } int main() { int graph[V][V] = { {0, 1, 0}, {1, 0, 1}, {0, 1, 0} }; bool visited[V] = {false}; bool hasCycle = false; for (int i = 0; i < V; i++) { if (!visited[i]) { if (dfs(i, -1, visited, graph)) { hasCycle = true; break; } } } if (hasCycle) { printf("Cycle detected\n"); } else { printf("No cycle detected\n"); } return 0; }
The graph is a simple chain with no cycles. DFS will not find any back edge, so it prints "No cycle detected".
#include <stdio.h> #include <stdbool.h> #define V 3 bool dfs(int v, int parent, bool visited[], int graph[V][V]) { visited[v] = true; for (int i = 0; i < V; i++) { if (graph[v][i]) { if (!visited[i]) { dfs(i, v, visited, graph); } else if (i != parent) { return true; } } } return false; } int main() { int graph[V][V] = { {0, 1, 1}, {1, 0, 1}, {1, 1, 0} }; bool visited[V] = {false}; bool hasCycle = false; for (int i = 0; i < V; i++) { if (!visited[i]) { if (dfs(i, -1, visited, graph)) { hasCycle = true; break; } } } if (hasCycle) { printf("Cycle detected\n"); } else { printf("No cycle detected\n"); } return 0; }
The DFS function calls itself recursively but does not return the result of the recursive call. So even if a cycle is found deeper, it is not propagated back, causing the function to always return false.
In an undirected graph, each edge is bidirectional. Without ignoring the parent, the DFS would always find the edge back to the parent as a cycle. So we exclude the parent to detect only real cycles.
#define V 7 int graph[V][V] = { {0,1,0,0,0,0,0}, {1,0,1,0,0,0,0}, {0,1,0,0,0,0,0}, {0,0,0,0,1,1,0}, {0,0,0,1,0,1,0}, {0,0,0,1,1,0,0}, {0,0,0,0,0,0,0} };
The graph has three connected components: nodes {0,1,2}, nodes {3,4,5}, and node {6} alone. The first component is a chain (no cycle), the second component forms a triangle (cycle), and the third is a single isolated node (no cycle). So only one component has a cycle.