Leetcode-802. 找到最终的安全状态 Find Eventual Safe State (拓扑排序) -python

题目

在有向图中, 我们从某个节点和每个转向处开始, 沿着图的有向边走。 如果我们到达的节点是终点 (即它没有连出的有向边), 我们停止。
现在, 如果我们最后能走到终点,那么我们的起始节点是最终安全的。 更具体地说, 存在一个自然数 K, 无论选择从哪里开始行走, 我们走了不到 K 步后必能停止在一个终点。
哪些节点最终是安全的? 结果返回一个有序的数组。
该有向图有 N 个节点,标签为 0, 1, …, N-1, 其中 N 是 graph 的节点数. 图以以下的形式给出: graph[i] 是节点 j 的一个列表,满足 (i, j) 是图的一条有向边。
链接:https://leetcode.com/problems/find-eventual-safe-states/

In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.

Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps.

Which nodes are eventually safe? Return them as an array in sorted order.

The directed graph has N nodes with labels 0, 1, …, N-1, where N is the length of graph. The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph.

Example:

Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.

思路及代码

拓扑排序(同207. 课程表)

  • 找到所有出度为0的点,依次删除
class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        outdegree = []
        outgraph = [[] for i in graph]
        for i in range(len(graph)):
            outdegree.append(len(graph[i]))
            for node in graph[i]:
                outgraph[node].append(i)
        zero = collections.deque([])
        ans = []
        for i in range(len(outdegree)):
            if outdegree[i] == 0:
                zero.append(i)
                ans.append(i)
        
        while zero:
            cur = zero.popleft()
            for nxt in outgraph[cur]:
                outdegree[nxt] -= 1
                if outdegree[nxt] == 0:
                    zero.append(nxt)
                    ans.append(nxt)
        return sorted(ans)
            

复杂度

T = O ( n + k l o g k ) T = O(n+klogk) T=O(n+klogk) # klogk是最后排序答案
S = O ( n ) S = O(n) S=O(n)

你可能感兴趣的:(Leetcode,leetcode,python,算法)