-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph2.cpp
More file actions
52 lines (45 loc) · 1.12 KB
/
graph2.cpp
File metadata and controls
52 lines (45 loc) · 1.12 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
42
43
44
45
46
47
48
49
50
51
52
//Finding cycle in undirected graph.
//Maintain a parent
//if vis[i]==0 ,answer will be what is returned from next step
//else check if the pre checked node is not the parent
#define pb push_back
bool find_cycle(vector<vector<int>> &graph,int s,vector<int> &visited,int par)
{
visited[s] = 1;
for (int i = 0;i < graph[s].size();i++)
{
if (visited[graph[s][i]] == 0)
{
if (find_cycle(graph,graph[s][i],visited,s) == true)
{
return true;
}
}
else
{
if (graph[s][i] != par)
{
return true;
}
}
}
return false;
}
int Solution::solve(int n, vector<vector<int> > &A) {
int m=A.size();
vector<vector<int>>v(n);
for(int i=0;i<n;i++)
{
v[A[i][0]-1].pb(A[i][1]-1);
v[A[i][1]-1].pb(A[i][0]-1);
}
vector<int>visited(n,0);
for(int i=0;i<n;i++)
{
if(visited[i]==0)
{
return find_cycle(v,i,visited,-1);
}
}
return 0;
}