leetcode 802. 找到最终的安全状态-DFS+颜色标注状态

在这里插入图片描述
链接:https://leetcode-cn.com/problems/find-eventual-safe-states/

解题思路:

  • 本题主要是判断图中结点如果在环内那么一定是不安全的,因为环内结点一定存在一条路径是无法到达最终结点的,所以采用DFS+颜色标注进行环的判断
  • 注意:
    1.颜色标注定义
    2.颜色状态转换
class Solution {
public:
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        int n = graph.size();
        vector<int>color(n,0);

        function<bool(int)> safe = [&](int x){
            if (color[x]>0){
                return color[x]==2;
            }
            color[x]=1;
            for(int y : graph[x]){
                if (!safe(y)){
                    return false;
                }
            }
            color[x]=2;
            return true;
        };
        vector<int>res;
        for(int i = 0;i<n;++i){
            if(safe(i)){
                res.emplace_back(i);
            }
        }
        return res;
    }
};
class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        length = len(graph)
        color = [0]*length#0表示没有遍历过,1表示存在环或者正在遍历,2表示安全结点
        def safe(x:int):
            if color[x] >0:
                return color[x]==2
            color[x]=1
            for y in graph[x]:
                if not safe(y):
                    return False
            color[x]=2
            return True
        return [i for i in range(length) if safe(i)]```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值