![]() |
VOOZH | about |
Given a directed graph with V vertices labeled from 0 to V-1 and a list of edges edges[][], where each edge is represented as [u, v] indicating a directed edge from vertex u to vertex v, find a Mother Vertex of the graph.
A Mother Vertex is a vertex from which all other vertices can be reached.
Example:
Input: V = 7, edges[][] = [[0, 1], [0, 2], [1, 3], [4, 1], [6, 4], [5, 6], [5, 2], [6, 0]]
Output: 5
Explanation: As shown in the above graph.Input: V = 5, edges[][] = [[0, 2], [0, 3], [1, 0], [2, 1], [3, 4]]
Output: 0
Explanation: Vertices 0, 1, and 2 can each reach all other vertices in the graph. Among them, 0 is the smallest, so the output is 0.
Table of Content
A straightforward (brute-force) approach is to run BFS (or DFS) from every vertex and check whether all other vertices are reachable from it. If such a vertex exists, it is a mother vertex. However, this approach is inefficient, as it requires performing a traversal for each vertex.
The approach is that if a mother vertex exists in a directed graph, it will be the last vertex to finish in a DFS traversal. This is because DFS may start from multiple unvisited vertices, forming a DFS forest. A mother vertex can reach all other vertices, so when DFS eventually starts from it, it will traverse the entire remaining graph in one go and finish last. Any earlier DFS starting points cannot reach all nodes (otherwise they would also be mother vertices). Therefore, the last finished vertex is the only possible candidate, and we finally verify it by checking whether it can reach all vertices.
Consider the following dry run:
V = 7, Edges = {{0, 1}, {0, 2}, {1, 3}, {4, 1}, {6, 4}, {5, 6}, {5, 2}, {6, 0}}
Final answer : 5
5