-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph-1
105 lines (95 loc) · 2.16 KB
/
graph-1
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
void dfsUtil(vector<int> g[], int v, bool visited[], vector<int>&res){
if(!visited[v]){
visited[v]=true;
res.push_back(v);
for(int i=0;i<g[v].size();++i){
dfsUtil(g,g[v][i],visited,res);
}
}
}
vector <int> dfs(vector<int> g[], int N)
{
bool visited[N]={false};
vector <int>res;
if(N==0)
return res;
dfsUtil(g,0,visited,res);
return res;
}
vector <int> bfs(vector<int> g[], int N) {
std::vector<int>res;
if(N==0)
return res;
std::queue<int>q;
bool visited[N]={false};
q.push(0);
while(!q.empty()){
int v = q.front();
if(!visited[v]){
visited[v]=true;
res.push_back(v);
for(int i=0;i<g[v].size();++i){
if(!visited[g[v][i]])
q.push(g[v][i]);
}
q.pop();
}
}
return res;
}
bool isCyclicUtil(vector<int>g[],int v,bool visited[],bool rec[]){
if(!visited[v]){
visited[v]=true;
rec[v]=true;
for(int i=0;i<g[v].size();++i){
if(!visited[g[v][i]]){
if(isCyclicUtil(g,g[v][i],visited,rec))
return true;
}else if(rec[g[v][i]])
return true;
}
}
rec[v]=false;
return false;
}
bool isCyclic(int V, vector<int> adj[])
{
bool visited[V]={false};
bool rec[V]={false};
for(int i=0;i<V;++i){
if(!visited[i]){
if(isCyclicUtil(adj,i,visited,rec))
return true;
}
}
return false;
}
bool isCyclicUtilUND(vector<int>g[],int v,bool visited[],int parent){
visited[v]=true;
//std::cout<<v<<" "<<parent<<"\n";
for(int i=0;i<g[v].size();++i){
if(!visited[g[v][i]]){
if(isCyclicUtilUND(g,g[v][i],visited,v))
return true;
}else if(g[v][i]!=parent)
return true;
}
return false;
}
bool isCyclicUND(vector<int> g[], int V)
{
bool visited[V]={false};
for(int i=0;i<V;++i){
if(!visited[i]){
if(isCyclicUtilUND(g,i,visited,-1))
return true;
}
}
return false;
}
int main()
{
cout<<"Hello World";
return 0;
}