MediumGraph

Minimum Number of Vertices to Reach All Nodes

1 approach, code in every language

Problem description

You are given a directed acyclic graph with n nodes labeled from 0 to n - 1, described by a list of directed edges where each edge [a, b] points from node a to node b. Starting from a chosen set of nodes and only walking along the direction of the edges, you want to be able to reach every node in the graph.

Return the smallest possible set of nodes from which all nodes are reachable. It is guaranteed that a unique solution exists.

You may return the nodes of the answer in any order.

Example 1

Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]

Output: [0,3]

From 0 you reach 1, 2, and 5; from 3 you reach 4 and then 2 and 5. Nodes 0 and 3 have no incoming edges, so they cannot be reached from anywhere else and must be included.

Example 2

Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]

Output: [0,2,3]

Nodes 0, 2, and 3 have indegree zero, so they must be starting points. From them nodes 1 and 4 are reachable, covering the entire graph.

Constraints

  • 2 <= n <= 10^5
  • 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
  • edges[i].length == 2
  • 0 <= a, b < n
  • a != b, and all edge pairs are unique
  • The graph is a directed acyclic graph (DAG)

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free