Given a connected undirected graph and a vertex in the graph, construct a directed graph such that any path in the directed graph leads to that particular vertex.

Undirected Graph

Consider the above connected undirected graph. Let the input vertex be 1. The goal is to convert the above graph to a directed graph such that any path in the directed graph leads to vertex 1. Below is one such graph.

Directed Graph

 
The idea is to perform Breadth–first search (BFS) or Depth–first search (DFS) on the undirected graph starting from the given vertex and add edges to the directed graph in the direction of the scan. A BFS Tree for the above graph that starts from vertex 1 would look like this.

BFS Tree for directed graph

After all the vertices are processed in our BFS or DFS, reverse all the directed graphs’ edges to have a path from every vertex in the directed graph to the input vertex. Please note that we can save reversing all edges if edges are added in reverse order in the directed graph.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

The time complexity of the above solution is the same as that of BFS, i.e., O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.