- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a directed acyclic graph, with n vertices and nodes are numbered from 0 to n-1, the graph is represented by an edge list, where edges[i] = (u, v) represents a directed edge from node u to node v. We have to find the smallest set of vertices from which all nodes in the graph are reachable. (We can return the vertices in any order).

So, if the input is like

then the output will be [0,2,3] because these two vertices are not reachable from any other vertices, so if we start from them we can cover all.

To solve this, we will follow these steps −

n := size of edges

all_nodes := a new set from range 0 to n

v := a new set

for each edge (i, j) in edges, do

add j into v

ans := remove all common edges from all_nodes and v from all_nodes

return ans

Let us see the following implementation to get better understanding −

def solve(edges): n = len(edges) all_nodes = set(range(n)) v = set() for edge in edges: v.add(edge[1]) ans = all_nodes - v return ans edges = [(0,1),(2,1),(3,1),(1,4),(2,4)] print(solve(edges))

[(0,1),(2,1),(3,1),(1,4),(2,4)]

{0, 2, 3}

- Related Questions & Answers
- Program to find number of minimum steps to reach last index in Python
- Program to find minimum number of hops required to reach end position in Python
- Program to find minimum number of buses required to reach final target in python
- Program to find minimum number of heights to be increased to reach destination in Python
- Program to find minimum jumps to reach home in Python
- Program to find number of good leaf nodes pairs using Python
- Program to find out the sum of minimum cost within a graph among all vertices in Python
- Program to find minimum number of cells it will take to reach bottom right corner in Python
- Program to find number of combinations of coins to reach target in Python
- C Program for Minimum number of jumps to reach the end
- Program to find minimum number of days to make m bouquets using Python
- Program to find number of given operations required to reach Target in Python
- Program to find out the minimum number of moves for a chess piece to reach every position in Python
- Program to find minimum number of movie theatres required to show all movies in python
- Program to find number of nodes in a range in Python

Advertisements