# 1557. Minimum Number of Vertices to Reach All Nodes ###### tags: `Python`,`Leetcode` https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ ## Code ``` python = class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: I = set(range(n)) for i in edges: if i[1] in I : I.remove(i[1]) return list(I) ``` ## 題意 * 這題題目有些難讀懂,主要大意就是 directed acyclic graph,graph 中的料是 int 0 ~ (n-1) * 題目希望找出這個 graph 的起始點有哪些,意即沒有人指向的 Edge **Example:** ``` Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]] Output: [0,3] Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3]. ``` ## 思路 * 所以我就創造一個 0 ~ (n-1) 的 set ,這裡不用 list 是因為查找資料的時間複雜度較高 O(n),set 只有 O(1) * 然後只要是在 edges[i][1] 的元素都代表示被指導的 edges ,他不會是我們題目要的答案(起始點),故把他 remove 掉 * 最後再轉成 list ,符合題目要求 ## 解法 ``` python = class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: I = set(range(n)) # 創造一個含有 int 0 ~ (n-1) 的 set for i in edges: if i[1] in I : # 如果每一組 pair 中被指向的那一個 在 set I 中,就把他 remove I.remove(i[1]) return list(I) # 轉回 list ,符合題目要求 ```