You are given a Directed Acyclic Graph (DAG) with ‘E’ edges and ‘V’ vertices. A DAG is a type of graph with no directed cycles.
You have been given a source vertex ‘S’. Your task is to find the distance between ‘S’ and the farthest vertex reachable from ‘S’?
Example: Given a DAG graph :
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.
Output Format :
For each test case, print the distance between ‘S’ and the farthest vertex reachable from ‘S’.
Note :
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
2
4 3
0 1
1 2
2 3
1
1 0
0
2
0
For first test case, the graph will be :
The farthest vertex in the above graph from vertex 1 is 3 whose distance from vertex 1 is 2.
For second test case, the graph will be :
There are no vertices present other than 0, therefore distance will be 0.
1
4 3
0 1
1 3
3 2
1
2
For the test case, the graph will be :
The farthest vertex in the above graph from vertex 1 is 2 whose distance from vertex 1 is 2.
Try to find the maximum number of vertices reachable from source by traversing.
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’)
O(|V| * (|V| + |E|)), where ‘V’ is the number of vertices and ‘E’ is the number of edges in the graph.
Total number of recursive calls for a vertex ‘V’ can be maximum upto (|V| + |E|) in which we will traverse every vertex and edge of the graph. Total number of vertices are ‘V’, therefore, the overall time complexity will be O(|V| * (|V| + |E|)).
O(|V| ^ 2), where ‘V’ is the number of vertices and ‘E’ is the number of edges in the graph.
For each vertex O(|V|), we store its adjacent neighbors O(|E|) it takes space O(|V| + |E|). But, in the worst case of a complete graph (each pair of vertices is connected by an edge), the space complexity will be O(|V| ^ 2).