forked from s-kachroo/SamsungPractice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetect cycle undirected graph.cpp
53 lines (41 loc) · 1.01 KB
/
detect cycle undirected graph.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
#include <iostream>
using namespace std;
int a[100][100], n;
bool findcycle(int st, bool visited[], int parent, int &prev){
visited[st]=true;
for(int j=0;j<n;j++){
if(a[st][j] == 1 && visited[j] == false){
if( findcycle(j, visited, st, prev) ){
if(st==prev){
cout << st << " ";
prev = -1;
}
else if(prev != -1){
cout << st << " ";
}
return true;
}
}
else if(a[st][j] == 1 && parent != j && visited[j] == true){
cout << st << " ";
prev = j;
return true;
}
}
return false;
}
int main(){
memset(a,0,sizeof(a));
int m;
cin >> n >> m;
int x,y;
while(m--){
cin>>x>>y;
a[x][y]=1;
a[y][x]=1;
}
bool visited[n] = {false};
int parent = -1, prev = -1;
findcycle(0,visited,parent,prev);
return 0;
}