leetcode - 802. Find Eventual Safe States

Description

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 (or another safe node).

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

Example 1:

复制代码
Illustration of graph
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 <= 10^4
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 * 10^4].

Solution

Topological sort. If we start from the terminal node, and remove its edges, then the next terminal node would be safe node. So this is actually a topological sort problem.

Time complexity: o ( e d g e s + n o d e s ) o(edges + nodes) o(edges+nodes)

Space complexity: o ( e d g e s + n o d e s ) o(edges + nodes) o(edges+nodes)

Code

python3 复制代码
class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        def build_graph(edges: list) -> tuple:
            graph = {i: [] for i in range(len(edges))}
            outdegree = {i: 0 for i in range(len(edges))}
            for i in range(len(edges)):
                for next_node in edges[i]:
                    graph[next_node].append(i)
                    outdegree[i] += 1
            return graph, outdegree
        # new_graph: {node: [node that points to this node]}
        # outdegree: {node: out_degree}
        new_graph, outdegree = build_graph(graph)
        queue = collections.deque([])
        res = set()
        for each_node in new_graph:
            if outdegree[each_node] == 0:
                queue.append(each_node)
        while queue:
            node = queue.popleft()
            if node in res:
                continue
            res.add(node)
            for neighbor_node in new_graph[node]:
                outdegree[neighbor_node] -= 1
                if outdegree[neighbor_node] == 0:
                    queue.append(neighbor_node)
        return list(sorted(res))
相关推荐
龙腾AI白云4 分钟前
大模型-AIGC技术在文本生成与音频生成领域的应用
算法
坚持编程的菜鸟4 小时前
LeetCode每日一题——困于环中的机器人
c语言·算法·leetcode·机器人
Aurorar0rua6 小时前
C Primer Plus Notes 09
java·c语言·算法
我不是QI8 小时前
DES 加密算法:核心组件、加解密流程与安全特性
经验分享·算法·安全·网络安全·密码学
前端小刘哥9 小时前
新版视频直播点播EasyDSS平台,让跨团队沟通高效又顺畅
算法
明月(Alioo)9 小时前
机器学习入门,无监督学习之K-Means聚类算法完全指南:面向Java开发者的Python实现详解
python·算法·机器学习
叶梅树9 小时前
从零构建A股量化交易工具:基于Qlib的全栈系统指南
前端·后端·算法
lingran__9 小时前
算法沉淀第三天(统计二进制中1的个数 两个整数二进制位不同个数)
c++·算法
MicroTech202510 小时前
微算法科技MLGO推出隐私感知联合DNN模型部署和分区优化技术,开启协作边缘推理新时代
科技·算法·dnn
小冯记录编程10 小时前
深入解析C++ for循环原理
开发语言·c++·算法