


Source node: 1
The farthest vertex in the above graph from vertex 1 is 2 via the route of vertex 3. So, the distance is 2.
The first line of input contains an integer ‘T’, the number of test cases.
The first line of each test case contains two single space-separated integers ‘V’ and ‘E’ representing the number of vertices and edges of the graph respectively.
The next ‘E’ lines will denote the edges of the graph where every edge is defined by two single space-separated integers ‘X' and 'Y', which signifies an edge from vertex 'X’ to vertex 'Y'.
The last line of each test case contains the single integer ‘S’, representing the Source vertex.
For each test case, print the distance between ‘S’ and the farthest vertex reachable from ‘S’.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= V <= 10^3
1 <= E <= 3*10^3
1 <= X, Y <= V - 1
0 <= S <= V - 1
Time Limit : 1 sec
The basic idea is to find the maximum number of vertices that are reachable from the ‘SOURCE’ vertex. We can find that using simple DFS traversal. We don’t need to use any ‘VISITED’ array as the graph given is DAG which means it contains no cycle.
Here is the algorithm :
DFS( ‘SOURCE’, ‘GRAPH’)
The approach is very similar to approach 1. We will try to avoid making repetitive recursive calls to the recursive functions if we have already calculated an answer for a specific vertex.
But how do we know that there will be repeated recursive calls ?
Let’s understand :
Let’s take an example.
Let the source vertex be 3 from which we have to calculate the maximum distance in the above graph.
As we can see, we made 2 recursive calls at vertex 0 which increases the time complexity in complex graphs. So, to avoid these repetitive calls, we can store previously calculated distances of vertices in an array.
The steps are similar to approach 1. Create an array (say, ‘DP’) and initialize it with -1.
We will also pass a ‘DP’ array with ‘SOURCE’ and ‘GRAPH’ as an argument this time.