-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMother vertex-gfg-Siddhartha Agarwal.cpp
84 lines (60 loc) · 1.17 KB
/
Mother vertex-gfg-Siddhartha Agarwal.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
81
82
83
84
// { Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/*
* Function to find if there is a mother vertex in the given graph
* V: number of vertices in the graph
* g[]: graph representation
*/
void dfs(int V, vector<int> g[], vector<bool> &v,int src)
{
v[src]=true;
for(int i:g[src])
{
if(v[i]==false)
{
dfs(V,g,v,i);
}
}
}
int findMother(int V, vector<int> g[])
{
vector<bool> v(V,false);
int mother=0;
for(int i=0;i<V;i++)
{
if(v[i]==false)
{
mother=i;
dfs(V,g,v,i);
}
}
vector<bool> vis(V,false);
dfs(V,g,vis,mother);
for(bool b:vis)
{
if(b==false)
return -1;
}
return mother;
}
// { Driver Code Starts.
int main()
{
int T;
cin>>T;
while(T--){
int num, edges;
cin>>num>>edges;
vector<int> adj[num];
int u, v;
while(edges--){
cin>>u>>v;
adj[u].push_back(v);
}
cout<<findMother(num, adj)<<endl;
}
return 0;
} // } Driver Code Ends