diff --git a/Algorithms/Graphs/cpp/CycleDetection.cpp b/Algorithms/Graphs/cpp/CycleDetection.cpp new file mode 100644 index 00000000..25a3d86f --- /dev/null +++ b/Algorithms/Graphs/cpp/CycleDetection.cpp @@ -0,0 +1,139 @@ + +#include +#include +#include +using namespace std; + +vector>* getEdgeSet(unordered_map*> &graph, int &edgeCount) { + + // NUMBER OF VERTICES + int V = graph.size(); + + vector> *v = new vector>(); + + for(int i=0; i size(); + for(int j=0; jat(j); + if(curr >= i) { + v->push_back(make_pair(i, curr)); + } + } + } + + edgeCount = v->size(); + return v; + +} + +int find(int *parent, int p) { + int currParent = p; + while(parent[currParent] != -1) { + currParent = parent[currParent]; + } + return currParent; +} + +void unionn(int *parent, int p1, int p2) { + parent[p2] = p1; +} + +bool detectCycle(unordered_map*> &graph) { + + // NUMBER OF VERTICES + int V = graph.size(); + + // NUMBER OF EDGES + int edgeCount = 0; + + // FUNCTION TO GET THE EDGE SET FROM AN ADJACENT LIST + vector> *edges = getEdgeSet(graph, edgeCount); + + // UTILITY PARENT SET FOR CYCLE DETECTION, INITIALISED WITH -1 + int *parent = new int[V]; + for(int i=0; iat(i).first); + int p2 = find(parent, edges->at(i).second); + + // IF P1 AND P2 ARE SAME THEN BOTH VERTICES LIE IN SAME SET + // INCLUDING THIS EDGE RESULTS IN A CYCLE + if(p1 == p2) + return true; + + // ELSE IF P1 NOT EQUAL TO P2, THEN BOTH VERTICES ARE IN DIFFERENT SETS + // INCLUDE BOTH IN SAME SET + unionn(parent, p1, p2); + } + + // NO CYCLE, RETURN FALSE + return false; + + +} + +int main() { + + /* + + 0 + / | \ + / | \ + 1 2 3 + | | \ + 4___5___6 7 + + */ + // INITIAL INPUT FOR NUMBER OF VERTICES AND EDGES + int V = 8, E = 8; + + // GRAPH AS ADJACENCY LIST + unordered_map *> graph; + for(int i=0; i(); + } + + // INPUT FOR EDGES + int **edges = new int*[E]; + for(int i=0; i push_back(edges[i][0]); + graph[edges[i][0]] -> push_back(edges[i][1]); + } + + // IF CYCLE EXISTS RETURNS TRUE + bool isCycle = detectCycle(graph); + + if(isCycle) + cout << "There is a cycle in the graph\n"; + else + cout << "No cycle in the graph\n"; + +} \ No newline at end of file