|
| 1 | +## 1557. 可以到达所有点的最少点数目 |
| 2 | +> https://leetcode-cn.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ |
| 3 | +
|
| 4 | + |
| 5 | +### Java |
| 6 | +```java |
| 7 | +/* |
| 8 | + * @Author: Goog Tech |
| 9 | + * @Date: 2020-09-15 16:12:07 |
| 10 | + * @LastEditTime: 2020-09-15 16:12:27 |
| 11 | + * @Description: https://leetcode-cn.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ |
| 12 | + * @FilePath: \leetcode-googtech\#1557. Minimum Number of Vertices to Reach All Nodes\Solution.java |
| 13 | + * @WebSite: https://algorithm.show/ |
| 14 | + */ |
| 15 | + |
| 16 | +class Solution { |
| 17 | + // 图数据结构 |
| 18 | + // 解题思路 : 遍历所有的边,使用集合存储所有有向边的终点, |
| 19 | + // 集合中的所有节点即为入度不为零的节点,剩下的所有节点即为入度为零,即没有前驱的节点. |
| 20 | + public List<Integer> findSmallestSetOfVertices(int n, List<List<Integer>> edges) { |
| 21 | + List<Integer> resultList = new ArrayList<>(); |
| 22 | + Set<Integer> endingSet = new HashSet<>(); |
| 23 | + for(List<Integer> edge : edges) endingSet.add(edge.get(1)); |
| 24 | + for(int i = 0; i < n; i++) { |
| 25 | + if(!endingSet.contains(i)) { |
| 26 | + resultList.add(i); |
| 27 | + } |
| 28 | + } |
| 29 | + return resultList; |
| 30 | + } |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +### Python |
| 35 | +```python |
| 36 | +''' |
| 37 | +Author: Goog Tech |
| 38 | +Date: 2020-09-15 16:12:13 |
| 39 | +LastEditTime: 2020-09-15 16:12:39 |
| 40 | +Description: https://leetcode-cn.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ |
| 41 | +FilePath: \leetcode-googtech\#1557. Minimum Number of Vertices to Reach All Nodes\Solution.py |
| 42 | +WebSite: https://algorithm.show/ |
| 43 | +''' |
| 44 | + |
| 45 | +class Solution(object): |
| 46 | + # 图数据结构 |
| 47 | + # 解题思路 : 遍历所有的边,使用集合存储所有有向边的终点, |
| 48 | + # 集合中的所有节点即为入度不为零的节点,剩下的所有节点即为入度为零,即没有前驱的节点. |
| 49 | + def findSmallestSetOfVertices(self, n, edges): |
| 50 | + """ |
| 51 | + :type n: int |
| 52 | + :type edges: List[List[int]] |
| 53 | + :rtype: List[int] |
| 54 | + """ |
| 55 | + endingSet = set(y for x, y in edges) |
| 56 | + return [i for i in range(n) if i not in endingSet] |
| 57 | +``` |
0 commit comments