leetcode 1557. Minimum Number of Vertices to Reach All Nodes(python)

1,195 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

描述

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:

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].

Example 2:

Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Output: [0,2,3]
Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.

Note:

  • 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.

解析

根据题意,就是给出了一个有向无环图,其中包含了 n 个节点,分别用索引 0 到 n-1 来表示节点,还有一个列表 edges ,其中每个元素都是一个子列表 [fromi, toi] 表示从节点 fromi 到 toi,题目要求我们找出最少的顶点个数,可以保证所有的节点都是可达的,这种节点集合是独一无二的,但是返回的结果顺序可以不同。

通过找规律可以发现,题目中要找的顶点都是只有出没有进的点,所以初始化 result 为所有节点的索引,然后遍历 edges 中的每个子列表 x ,只要 x[1] 在 result 说明其可达,所以从 result 中删掉该元素,遍历结束剩下的节点就是满足题意的顶点集合。

解答

class Solution(object):
    def findSmallestSetOfVertices(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        result = set(range(n))
        for x,y in edges:
            if y in result:
                result.remove(y)
        return list(result)
        	      
		

运行结果

Runtime: 1036 ms, faster than 60.82% of Python online submissions for Minimum Number of Vertices to Reach All Nodes.
Memory Usage: 54.6 MB, less than 49.48% of Python online submissions for Minimum Number of Vertices to Reach All Nodes.

原题链接:leetcode.com/problems/mi…

您的支持是我最大的动力