From 5b2d18a5e93977da0ea2105d31f242c071a075aa Mon Sep 17 00:00:00 2001 From: Drashti Koladiya <58821355+DrashtiKoladiya@users.noreply.github.com> Date: Thu, 15 Oct 2020 11:50:15 +0530 Subject: [PATCH] Created find-MotherVertex.cpp --- Graph/find-MotherVertex.cpp | 72 +++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Graph/find-MotherVertex.cpp diff --git a/Graph/find-MotherVertex.cpp b/Graph/find-MotherVertex.cpp new file mode 100644 index 0000000..ac65104 --- /dev/null +++ b/Graph/find-MotherVertex.cpp @@ -0,0 +1,72 @@ +//code for finding mother vertex in the given graph + +/* + ->mother vertex is the vertex from which all other vertex can be visited. + ->now if the vertex is mother vertex then it's finished time will be maximum.. + ->there may be more than one mother vertex. + +*/ + +#include +using namespace std; + +class Graph +{ + long long int V; + //No of vertices + + // Adjacency list of the given graph + vector< vector > adj; + + //constructor + Graph(long long int V) + { + adj.assign(V, vector()); + } + + void addEdge(long long int v,long long int u); + + long long int findMotherVertex(); + void DFS(long long int src,vector &visited); +}; + +void Graph::addEdge(long long int v,long long int u) +{ + //function for adding an edge between vertex v and vertex u + adj[v].push_back(u); +} + +long long int Graph::findMotherVertex() +{ + vector visited(V,false); + + //store motheVertex in a variable + long long int motherVertex; + + for(long long int i=1;i<=V;i++) + { + if(!visited[i]) + { + DFS(i,visited); + motherVertex = i; + } + } + + return motherVertex; +} + +void Graph::DFS(long long int src,vector &visited) +{ + //mark the given vertex as visited + visited[src]=true; + + // iterate over adjancent vertexes of the given vertex + for(auto x:adj[src]) + { + // If the vertex is not visited then run DFS from that vertex + if(!visited[x]) + { + DFS(x,visited); + } + } +}