Find all the Mother Vertices of a graph
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.
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.
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.
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 :
All Mother vertices of the graph are : 0 1 4
Time Complexity: O(V+E)
Space Complexity: O(V+E)