802. Find Eventual Safe States

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了802. Find Eventual Safe States相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/find-eventual-safe-states/description/

class Solution {
public:
    vector<bool> visited;
    vector<int> mem;    // -1 unknown, 0 unsafe, 1 safe.
    int n;
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        n = graph.size();
        mem = vector<int>(n, -1);
        visited = vector<bool>(n, false);
        for (int i = 0; i < n; i++)
            dfs(graph, i);
        
        vector<int> res;
        for (int i = 0; i < n; i++)
            if (mem[i] == 1)
                res.push_back(i);
        return res;
    }
    bool dfs(vector<vector<int>>& graph, int i) {
        // check if i is evetually safe
        if (mem[i] != -1)   return mem[i] == 1;
        
        bool res = true;
        if (visited[i]) {  // A loop
            res = false;
        }
        else {
            visited[i] = true;
            for (auto j : graph[i]) {
                if (!dfs(graph, j)) {
                    res = false;
                    break;
                }
            }
            // visited[i] = false;    // This line is optional, since we‘ve cached the result for i in mem.
        }
        mem[i] = res;
        return res;
    }
};

  

以上是关于802. Find Eventual Safe States的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 802. Find Eventual Safe States 找到最终的安全状态

leetcode 802. 找到最终的安全状态(Find Eventual Safe States)

[LeetCode] Find Eventual Safe States 找到最终的安全状态

hdu 1596 find the safest road

HDU1596 find the safest road---(最短路径dijkstra,#变形#)

2018-2019 ACM-ICPC, Asia East Continent Final L Eventual … Journey