Longest Path in Directed Acyclic Graph (DAG)
Given a Directed Acyclic Graph (DAG) with a specific number of edges and vertices, your task is to determine the longest path reachable from a given source vertex.
Input:
The first line describes an integer 'T', representing the number of test cases.
Each test case begins with a pair of integers 'V' and 'E', representing the number of vertices and edges.
The next 'E' lines contain two space-separated integers 'X' and 'Y', describing a directed edge from vertex 'X' to vertex 'Y'.
The last line in each test case provides a single integer 'S' representing the source vertex.
Output:
For each test case, output the distance to the farthest vertex reachable from vertex 'S'.
Example:
A DAG might look like:
Source node: 1 The farthest vertex in the given graph from vertex 1 is 2, via the path through vertex 3. Hence, the distance is 2.
Constraints:
1 <= T <= 10
1 <= V <= 10^3
1 <= E <= 3*10^3
1 <= X, Y <= V - 1
0 <= S <= V - 1
Note: Implement the function only; input/output has been handled.

AnswerBot
4mo
Find the longest path in a Directed Acyclic Graph (DAG) from a given source vertex.
Use Topological Sorting to find the longest path in the DAG.
Initialize distances to all vertices as minus infinite ex...read more
Help your peers!
Add answer anonymously...
Amazon Software Developer Intern interview questions & answers
A Software Developer Intern was asked 4mo agoQ. Given a linked list, find the n'th node from the end of the list.
A Software Developer Intern was asked 4mo agoQ. Given a tree, find its diameter (the longest path between two nodes in the tree)...read more
A Software Developer Intern was asked 4mo agoQ. Given a matrix, find the shortest distance between two given points located anyw...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked 4mo agoQ1. Given a linked list, find the n'th node from the end of the list.
A Software Developer Intern was asked 4mo agoQ2. Given a tree, find its diameter (the longest path between two nodes in the tree)...read more
A Software Developer Intern was asked 4mo agoQ3. Given a matrix, find the shortest distance between two given points located anyw...read more
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

