A root vertex of a directed graph is a vertex u with a directed path from u to v for every pair of vertices (u, v) in the graph. In other words, all other vertices in the graph can be reached from the root vertex.

A graph can have multiple root vertices. For example, each vertex in a strongly connected component is a root vertex. In such cases, the solution should return anyone of them. If the graph has no root vertices, the solution should return -1.

 
The root vertex is 4 since it has a path to every other vertex in the following graph:

Root of a directed graph

Practice this problem

A simple solution would be to perform a DFS (or BFS) on all the graph vertices until we encounter a vertex from which every other vertex can be reached. The time complexity of this solution is O(V × (V + E)), where V and E are the total number of vertices and edges in the graph, respectively.

Another solution is to perform topological sorting on the graph. This will reduce the time complexity to linear but may not work for the cyclic graphs.

 
We can easily find the root vertex in O(n + m) time using a DFS. The idea is to start a DFS procedure from any node of the graph and mark the visited vertices. If there are any unvisited vertices, start the DFS again until all vertices are visited. Finally, the vertex having the maximum departure time in DFS is a candidate for the root vertex. We can easily check whether that vertex is a root vertex or not by doing a DFS (or BFS) on it.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The root vertex is 4

Java


Download  Run Code

Output:

The root vertex is 4

Python


Download  Run Code

Output:

The root vertex is 4