-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCycleExistInGraph.cpp
58 lines (47 loc) · 1.3 KB
/
CycleExistInGraph.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
#include <bits/stdc++.h>
#define mx 1000000
using namespace std;
/***************************************************************************************/
vector<int> graph[mx];
bool vis[mx];
bool dfs(int vertex, int parent) {
vis[vertex] = true;
bool isLoopExist = false;
for (int i = 0; i < graph[vertex].size(); i++) {
int next = graph[vertex][i];
if (vis[next] && next != parent) {
return true;
}
else if (!vis[next]) {
isLoopExist |= dfs(next, vertex);
}
}
return isLoopExist;
}
void solve() {
int nodes, edge, source;
cin >> nodes >> edge ;
for (int i = 0; i < edge; i++) {
int v1, v2;
cin >> v1 >> v2;
graph[v1].push_back(v2);
graph[v2].push_back(v1);
}
bool isLoopExist = false;
for (int i = 0; i < nodes; i++) {
if (vis[i]) {
continue;
}
else {
if (isLoopExist)
{
break;
}
isLoopExist |= dfs(i, 0);
}
}
cout << isLoopExist;
}
int main() {
solve();
}