Minimum Number of Vertices to Reach All Nodes Problem Statement
In a directed acyclic graph with 'N' nodes, given a matrix 'edges' of size M x 2 representing 'M' edges where each edge is directed from node edges[i][0] to node edges[i][1], find the smallest set of vertices from which all the nodes in the graph are reachable.
Input:
The first line contains a single integer ‘T’, denoting the number of test cases.
The first line of each test case contains two integers ‘N’ and ‘M’, where ‘N’ represents the number of vertices and ‘M’ denotes the number of edges.
The next ‘M’ lines of each test case contain two integers ‘X’ and ‘Y’, where ‘X’ is the start vertex and ‘Y’ is the end vertex of a directed edge.
Output:
For each test case, output the smallest set of vertices from which all the nodes in the graph are reachable, in sorted order.
Print each test case result on a new line.
Example:
Sample Input:
2
6 5
0 1
0 2
2 5
3 4
4 2
5 4
0 1
2 1
1 4
2 4
Sample Output:
0 3
0 2 3
Explanation of Sample Output:
In the first test case, the vertices 0 and 3 can collectively reach all other nodes in the graph.
In the second test case, the vertices 0, 2, and 3 can collectively reach all nodes.
Constraints:
- 1 ≤ T ≤ 5
- 2 ≤ N ≤ 105
- 1 ≤ M ≤ 105
- 0 ≤ X, Y ≤ N - 1
- Time Limit: 1 second
Note:
Nodes are numbered from 0 to N - 1.
The provided graph is connected.
Vertices in the result should be printed in sorted order.
Be the first one to answer
Add answer anonymously...
Top Morgan Stanley Technology Analyst interview questions & answers
Popular interview questions of Technology Analyst
Top HR questions asked in Morgan Stanley Technology Analyst
>
Morgan Stanley Technology Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app