-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph-IsCyclic.cpp
91 lines (80 loc) · 1.99 KB
/
Graph-IsCyclic.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
using namespace std;
#include <vector>
#include <cmath>
#include <time.h>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <list>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <bits/stdc++.h>
// Note: 'v' num of vertices => nodes val lies betn 1 to 'v'
class Graph{
private:
int vert;
int edge;
vector<vector<int>> graph;
vector<bool> isVisited;
public:
Graph(int v, int e){
vert= v, edge= e;
graph.resize(vert+1);
isVisited.resize(vert+1, false);
}
void adjacencyList(){
cout<< "Enter Connected Nodes: "<< endl;
for(int i=0;i<edge;i++){
int v1, v2;
cin>> v1>> v2;
graph[v1].push_back(v2);
graph[v2].push_back(v1);
}
}
void dfs(int vertex){
if(isVisited[vertex]) return;
// process curr vertex
isVisited[vertex]= true;
// cout<< vertex<< " ";
for(int child: graph[vertex]) dfs(child);
}
int connectedComponents(){
int count= 0;
for(int vertex=1;vertex<=vert;vertex++){
if(isVisited[vertex]) continue;
count++;
dfs(vertex);
}
return count;
}
bool helper(int vertex, int parent= -1){
isVisited[vertex]= true;
for(int child: graph[vertex]){
if(isVisited[child] and child!=parent) return true;
if(isVisited[child]) continue;
if(helper(child, vertex)) return true;
}
return false;
}
bool isCyclic(){
// There can be more than 1 connected components
bool doesLoopExist= false;
for(int v=1;v<=vert;v++){
if(isVisited[v]) continue;
doesLoopExist|= helper(v);
if(doesLoopExist) break;
}
return doesLoopExist;
}
};
int main(){
Graph gph(8, 6);
gph.adjacencyList();
cout<< gph.isCyclic();
return 0;
}