-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleDetectionUsingBFS.cpp
More file actions
41 lines (40 loc) · 1.04 KB
/
Copy pathCycleDetectionUsingBFS.cpp
File metadata and controls
41 lines (40 loc) · 1.04 KB
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
#include<bits/stdc++.h>
using namespace std;
bool bfs(int node, int parent, vector<vector<int>> graph, vector<bool>& visited) {
queue<pair<int,int>> q;
q.push({node, parent});
visited[node] = true;
while(!q.empty()) {
int curr = q.front().first;
int parent = q.front().second;
for(int a : graph[curr]) {
if(!visited[a]) {
q.push({a, curr});
visited[a] = true;
} else if(a != parent) {
return true;
}
}
q.pop();
}
return false;
}
int main() {
int n, m, from, to;
cin >> n >> m;
vector<vector<int>> graph(n);
for(int i = 0; i < m; ++i) {
cin >> from >> to;
graph[from].push_back(to);
graph[to].push_back(from);
}
vector<bool> visited(n, false);
for(int i = 0; i < n; ++i) {
if(!visited[i] && bfs(i, -1, graph, visited)) {
printf("Contains Cycle\n");
return 0;
}
}
printf("Doesn't contain cycle\n");
return 0;
}