1557. Minimum Number of Vertices to Reach All Nodes
Medium
Previous1539. Kth Missing Positive NumberNext1608. Special Array With X Elements Greater Than or Equal X
Last updated
Medium
Last updated
Given a directed acyclic graph, with n
vertices numbered from 0
to n-1
, and an array edges
where edges[i] = [fromi, toi]
represents a directed edge from node fromi
to node toi
.
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
Example 2:
Constraints:
2 <= n <= 10^5
1 <= edges.length <= min(10^5, n * (n - 1) / 2)
edges[i].length == 2
0 <= fromi, toi < n
All pairs (fromi, toi)
are distinct.
統計每個點的 indegree,indegree 等於零代表:如果不從該節點出發,則永遠走不到,因次加入答案。不等於零則是遲早會走到。
Runtime: 166 ms, faster than 100%
Memory Usage: 16.1 MB, less than 96.97%