-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cycle Detection In Undirected Graph CodingNinjas.cpp
80 lines (61 loc) · 1.69 KB
/
Cycle Detection In Undirected Graph CodingNinjas.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
// dfs
// tc=o(n)
// sc=o(n)
#include<bits/stdc++.h>
using namespace std;
bool dfs(int node, int parent, vector<vector<int>>& adj, vector<bool>& visi, int n){
visi[node]=true;
for(int i: adj[node]){
if(!visi[i]){
if(dfs(i,node,adj,visi,n)){
return true;
}
}
else if(parent!=i) return true;
}
return false;
}
string cycleDetection(vector<vector<int>>& edges, int n, int m){
vector<vector<int>> adj(n+1,vector<int>());
for(int i=0;i<m;i++){
adj[edges[i][0]].push_back(edges[i][1]);
adj[edges[i][1]].push_back(edges[i][0]);
}
vector<bool> visi(n+1,false);
for(int i=1;i<=n;i++){
if(!visi[i]){
if(dfs(i,-1,adj, visi,n)) return "Yes";
}
}
return "No";
}
// bfs
// tc=o(n)
// sc=o(n)
#include<bits/stdc++.h>
using namespace std;
string cycleDetection (vector<vector<int>>& edges, int n, int m){
vector<vector<int>> adj(n+1,vector<int>());
for(int i=0;i<edges.size();i++){
adj[edges[i][0]].push_back(edges[i][1]);
adj[edges[i][1]].push_back(edges[i][0]);
}
vector<bool> visi(n+1,false);
for(int node=1;node<=n;node++){
if(visi[node]==false){
queue<pair<int,int>> q;
q.push({node,-1});
while(!q.empty()){
pair<int,int> front=q.front();
visi[front.first]=true;
q.pop();
for(int i: adj[front.first]){
if(i==front.second) continue;
else if(visi[i]) return "Yes";
else q.push({i,front.first});
}
}
}
}
return "No";
}