Program to find minimum number of vertices to reach all nodes using Python


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 −

Example

 Live Demo

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))

Input

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

Output

{0, 2, 3}

Updated on: 29-May-2021

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements