|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// DFS function to detect cycle in a directed graph |
| 6 | +bool dfsCycle(int v, const vector<vector<int>>& graph, vector<bool>& visited, vector<bool>& recStack) { |
| 7 | + visited[v] = true; |
| 8 | + recStack[v] = true; |
| 9 | + |
| 10 | + // Explore all neighbors |
| 11 | + for (int neighbor : graph[v]) { |
| 12 | + // If neighbor is not visited, do DFS on it |
| 13 | + if (!visited[neighbor]) { |
| 14 | + if (dfsCycle(neighbor, graph, visited, recStack)) |
| 15 | + return true; |
| 16 | + } |
| 17 | + // If neighbor is in the recursion stack, cycle detected |
| 18 | + else if (recStack[neighbor]) { |
| 19 | + return true; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // Remove vertex from recursion stack before returning |
| 24 | + recStack[v] = false; |
| 25 | + return false; |
| 26 | +} |
| 27 | + |
| 28 | +// Function to detect cycle in the entire graph |
| 29 | +bool detectCycle(const vector<vector<int>>& graph, int V) { |
| 30 | + vector<bool> visited(V, false); |
| 31 | + vector<bool> recStack(V, false); |
| 32 | + |
| 33 | + for (int i = 0; i < V; i++) { |
| 34 | + if (!visited[i]) { |
| 35 | + if (dfsCycle(i, graph, visited, recStack)) |
| 36 | + return true; |
| 37 | + } |
| 38 | + } |
| 39 | + return false; |
| 40 | +} |
| 41 | + |
| 42 | +int main() { |
| 43 | + int V, E; |
| 44 | + cout << "Enter the number of vertices: "; |
| 45 | + cin >> V; |
| 46 | + cout << "Enter the number of edges: "; |
| 47 | + cin >> E; |
| 48 | + |
| 49 | + // Initialize graph as an adjacency list (0-indexed vertices) |
| 50 | + vector<vector<int>> graph(V); |
| 51 | + cout << "Enter each edge (u v) [directed edge from u to v]:" << endl; |
| 52 | + for (int i = 0; i < E; i++) { |
| 53 | + int u, v; |
| 54 | + cin >> u >> v; |
| 55 | + graph[u].push_back(v); |
| 56 | + } |
| 57 | + |
| 58 | + if (detectCycle(graph, V)) |
| 59 | + cout << "Cycle detected in the graph." << endl; |
| 60 | + else |
| 61 | + cout << "No cycle detected in the graph." << endl; |
| 62 | + |
| 63 | + return 0; |
| 64 | +} |
0 commit comments