# Find all the Mother Vertices of a graph

• Difficulty Level : Hard
• Last Updated : 02 Sep, 2021

Mother vertex: A mother vertex in a Graph G = (V, E) is a vertex v such that all other vertices in  G can be reached by a path from v. There can be zero, one, or more than one mother vertices in a graph. We need to find all the mother vertices in the given graph.

Example :

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input : Given graph below
Output : 0 1 4
Explanation : In the given graph, the mother vertices are 0, 1 and 4 as there exists a path to each vertex from these vertices. Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive approach :
A trivial approach will be to perform a DFS or a BFS on all the vertices and find whether we can reach all the vertices from that vertex.

Time Complexity: O(V(E+V))

Efficient Approach :

• Find any mother vertex v in the given graph G using this algorithm.
• If a mother vertex exists, then the set of vertices of Graph G that form a strongly connected component and contains v is the set of all the mother vertices of the graph.

How does the above idea work?
If a mother vertex exists for a graph, then all the mother vertices are the vertices of the strongly connected component which contains the mother vertex because if v is a mother vertex and there exists a path from u->v then u must be a mother vertex as well.

Below is the implementation of the above approach :

## C++

 `// C++ program to find all the mother vertices``#include ``using` `namespace` `std;` `// This function does DFS traversal``// from given node u, and marks the``// visited nodes in the visited array``void` `dfs_helper(``int` `u, vector >& adj,``                ``bool` `visited[])``{``    ``if` `(visited[u])``        ``return``;` `    ``visited[u] = ``true``;` `    ``for` `(``auto` `v : adj[u]) {``        ``if` `(!visited[v])``            ``dfs_helper(v, adj, visited);``    ``}``}` `// Function that stores the adjacency``// list of the transpose graph of the``// given graph in the trans_adj vector``void` `getTransposeGraph(vector >& adj,``                       ``vector >& trans_adj)``{``    ``for` `(``int` `u = 0; u < adj.size(); u++) {``        ``for` `(``auto` `v : adj[u]) {``            ``trans_adj[v].push_back(u);``        ``}``    ``}``}` `// Initializes all elements of visited``// array with value false``void` `initialize_visited(``bool` `visited[], ``int` `n)``{``    ``for` `(``int` `u = 0; u < n; u++)``        ``visited[u] = ``false``;``}` `// Returns the list of mother``// vertices. If the mother vertex``// does not exists returns -1``vector<``int``> findAllMotherVertices(vector >& adj)``{``    ``int` `n = adj.size();``    ``bool` `visited[n];` `    ``// Find any mother vertex``      ``// in given graph, G``    ``initialize_visited(visited, n);``    ``int` `last_dfs_called_on = -1;` `    ``for` `(``int` `u = 0; u < n; u++) {``        ``if` `(!visited[u]) {``            ``dfs_helper(u, adj, visited);``            ``last_dfs_called_on = u;``        ``}``    ``}` `    ``// Check if we can reach``       ``// all vertices from``    ``// last_dfs_called_on node``    ``initialize_visited(visited, n);``    ``dfs_helper(last_dfs_called_on, adj, visited);` `    ``for` `(``int` `u = 0; u < n; u++) {``        ` `          ``// Check of the mother vertex``        ``// exist else return -1``          ``if` `(!visited[u]) {``            ``vector<``int``> emptyVector;``            ``emptyVector.push_back(-1);` `            ``return` `emptyVector;``        ``}``    ``}` `    ``// Now in G_transpose, do DFS``    ``// from that mother vertex,``    ``// and we will only reach the``      ``// other mother vertices of G``    ``int` `motherVertex = last_dfs_called_on;` `    ``// trans_adj is the transpose``    ``// of the given Graph``    ``vector > trans_adj(n);` `    ``// Function call to get``      ``// the transpose graph``    ``getTransposeGraph(adj, trans_adj);` `    ``// DFS from that mother vertex``    ``// in the transpose graph and the``    ``// visited nodes are all the``    ``// mother vertices of the given``    ``// graph G``    ``initialize_visited(visited, n);``    ``dfs_helper(motherVertex, trans_adj, visited);` `    ``// Vector to store the list``      ``// of mother vertices``    ``vector<``int``> ans;` `    ``for` `(``int` `u = 0; u < n; u++) {``        ``if` `(visited[u])``            ``ans.push_back(u);``    ``}` `    ``// Return the required list``    ``return` `ans;``}` `// Driver Code``int` `main()``{``    ``// No. of nodes``    ``int` `V = 8;``    ``vector > adj(V);` `    ``adj.push_back(1);``    ``adj.push_back(2);``    ``adj.push_back(4);``    ``adj.push_back(5);``    ``adj.push_back(3);``    ``adj.push_back(6);``    ``adj.push_back(2);``    ``adj.push_back(7);``    ``adj.push_back(0);``    ``adj.push_back(5);``    ``adj.push_back(6);``    ``adj.push_back(5);``    ``adj.push_back(7);` `    ``// Function call to find the mother vertices``    ``vector<``int``> motherVertices = findAllMotherVertices(adj);` `    ``// Print answer``    ``if` `(motherVertices == -1)``        ``cout << ``"No mother vertex exists"``;``    ``else` `{``        ``cout << ``"All Mother vertices of the graph are : "``;``        ``for` `(``int` `v : motherVertices)``            ``cout << v << ``" "``;``    ``}` `    ``return` `0;``}`

## Java

 `// Java program to find all the mother vertices``import` `java.util.*;` `class` `GFG{` `// This function does DFS traversal``// from given node u, and marks the``// visited nodes in the visited array``static` `void` `dfs_helper(``int` `u, Vector[] adj,``                ``boolean` `visited[])``{``    ``if` `(visited[u])``        ``return``;` `    ``visited[u] = ``true``;` `    ``for` `(``int` `v : adj[u]) {``        ``if` `(!visited[v])``            ``dfs_helper(v, adj, visited);``    ``}``}` `// Function that stores the adjacency``// list of the transpose graph of the``// given graph in the trans_adj vector``static` `void` `getTransposeGraph(Vector[] adj,``        ``Vector[] trans_adj)``{``    ``for` `(``int` `u = ``0``; u < adj.length; u++) {``        ``for` `(``int` `v : adj[u]) {``            ``trans_adj[v].add(u);``        ``}``    ``}``}` `// Initializes all elements of visited``// array with value false``static` `void` `initialize_visited(``boolean` `visited[], ``int` `n)``{``    ``for` `(``int` `u = ``0``; u < n; u++)``        ``visited[u] = ``false``;``}` `// Returns the list of mother``// vertices. If the mother vertex``// does not exists returns -1``static` `Vector findAllMotherVertices(Vector[] adj)``{``    ``int` `n = adj.length;``    ``boolean` `[]visited = ``new` `boolean``[n];` `    ``// Find any mother vertex``      ``// in given graph, G``    ``initialize_visited(visited, n);``    ``int` `last_dfs_called_on = -``1``;` `    ``for` `(``int` `u = ``0``; u < n; u++) {``        ``if` `(!visited[u]) {``            ``dfs_helper(u, adj, visited);``            ``last_dfs_called_on = u;``        ``}``    ``}` `    ``// Check if we can reach``       ``// all vertices from``    ``// last_dfs_called_on node``    ``initialize_visited(visited, n);``    ``dfs_helper(last_dfs_called_on, adj, visited);` `    ``for` `(``int` `u = ``0``; u < n; u++) {``        ` `          ``// Check of the mother vertex``        ``// exist else return -1``          ``if` `(!visited[u]) {``            ``Vector emptyVector = ``new` `Vector();``            ``emptyVector.add(-``1``);` `            ``return` `emptyVector;``        ``}``    ``}` `    ``// Now in G_transpose, do DFS``    ``// from that mother vertex,``    ``// and we will only reach the``      ``// other mother vertices of G``    ``int` `motherVertex = last_dfs_called_on;` `    ``// trans_adj is the transpose``    ``// of the given Graph``    ``Vector []trans_adj = ``new` `Vector[n];``    ``for` `(``int` `i = ``0``; i < trans_adj.length; i++)``        ``trans_adj[i] = ``new` `Vector();` `    ``// Function call to get``      ``// the transpose graph``    ``getTransposeGraph(adj, trans_adj);` `    ``// DFS from that mother vertex``    ``// in the transpose graph and the``    ``// visited nodes are all the``    ``// mother vertices of the given``    ``// graph G``    ``initialize_visited(visited, n);``    ``dfs_helper(motherVertex, trans_adj, visited);` `    ``// Vector to store the list``      ``// of mother vertices``    ``Vector ans = ``new` `Vector();` `    ``for` `(``int` `u = ``0``; u < n; u++) {``        ``if` `(visited[u])``            ``ans.add(u);``    ``}` `    ``// Return the required list``    ``return` `ans;``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``// No. of nodes``    ``int` `V = ``8``;``    ``Vector[] adj = ``new` `Vector[V];``    ``for` `(``int` `i = ``0``; i < adj.length; i++)``        ``adj[i] = ``new` `Vector();``    ``adj[``0``].add(``1``);``    ``adj[``1``].add(``2``);``    ``adj[``1``].add(``4``);``    ``adj[``1``].add(``5``);``    ``adj[``2``].add(``3``);``    ``adj[``2``].add(``6``);``    ``adj[``3``].add(``2``);``    ``adj[``3``].add(``7``);``    ``adj[``4``].add(``0``);``    ``adj[``4``].add(``5``);``    ``adj[``5``].add(``6``);``    ``adj[``6``].add(``5``);``    ``adj[``6``].add(``7``);` `    ``// Function call to find the mother vertices``    ``Vector motherVertices = findAllMotherVertices(adj);` `    ``// Print answer``    ``if` `(motherVertices.get(``0``) == -``1``)``        ``System.out.print(``"No mother vertex exists"``);``    ``else` `{``        ``System.out.print(``"All Mother vertices of the graph are : "``);``        ``for` `(``int` `v : motherVertices)``            ``System.out.print(v+ ``" "``);``    ``}` `}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``
Output
`All Mother vertices of the graph are : 0 1 4 `

Time Complexity: O(V+E)
Space Complexity: O(V+E)

My Personal Notes arrow_drop_up