Skip to content

Commit aefd7c5

Browse files
committed
Minimum Number of Vertices to Reach All Nodes
1 parent 3d4a86a commit aefd7c5

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Given a directed acyclic graph, with n vertices numbered from 0 to n-1,
2+
# and an array edges where edges[i] = [from[i], to[i]] represents a directed edge from node from[i] to node to[i].
3+
#
4+
# Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
5+
#
6+
# Notice that you can return the vertices in any order.
7+
8+
"""
9+
>>> Solution().findSmallestSetOfVertices(6, [[0,1],[0,2],[2,5],[3,4],[4,2]])
10+
[0, 3]
11+
>>> Solution().findSmallestSetOfVertices(5, [[0,1],[2,1],[3,1],[1,4],[2,4]])
12+
[0, 2, 3]
13+
"""
14+
from typing import List
15+
16+
17+
class Solution:
18+
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
19+
nodes = [False for _ in range(n)]
20+
21+
for a, b in edges:
22+
nodes[b] = True
23+
24+
return [i for i, node in enumerate(nodes) if not node]

0 commit comments

Comments
 (0)