LeetCode 802. Find Eventual Safe States - 拓扑排序(Topological Sort)系列题5

There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].

A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node.

Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

Example 1:

LeetCode 802. Find Eventual Safe States - 拓扑排序(Topological Sort)系列题5_第1张图片

Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.

Example 2:

Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.

Constraints:

  • n == graph.length
  • 1 <= n <= 104
  • 0 <= graph[i].length <= n
  • 0 <= graph[i][j] <= n - 1
  • graph[i] is sorted in a strictly increasing order.
  • The graph may contain self-loops.
  • The number of edges in the graph will be in the range [1, 4 * 104].

这题跟前面刷过的拓扑排序(Topological Sort)题比如LeetCode 444. Sequence Reconstruction略有不同,是拓扑排序(Topological Sort)的换一种考法,也是一道考验我们是否彻底掌握拓扑排序的经典题。

这题的关键是分析题意,分析明白了代码就很简单了跟其他拓扑排序题是一样的。拓扑排序的核心就是把图中的边一条条地剔除直到最后,首先是要确定从哪些顶点开始剔除边。题目是要找出所有safe nodes, 所谓safe node是从这个顶点出发所有路径都能到达终点terminal node。很显然terminal node就是safe node,terminal node是只有指向该顶点的边而没有指向其它顶点的边。因此,这题要用拓扑排序法的话需要用到出度Outdegree而不是常规的入度Indegree。从出度为0的顶点出发依次剔除边。

class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        n = len(graph)
        outdegree = [0] * n
        graph1 = [[] for i in range(n)]
        
        for i in range(n):
            for j in graph[i]:
                outdegree[i] += 1
                graph1[j].append(i)
        
        q = deque()
        for i in range(n):
            if outdegree[i] == 0:
                q.append(i)
        
        while q :
            u = q.popleft()
            
            for v in graph1[u]:
                outdegree[v] -= 1
                if outdegree[v] == 0:
                    q.append(v)
                    
        res = []
        for i in range(n):
            if outdegree[i] == 0:
                res.append(i)
        
        return res

 

你可能感兴趣的:(Leetcode刷题笔记,Sort),leetcode,算法,python,数据结构,拓扑排序)