802. Find Eventual Safe States

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;    <strong>// This line is optional, since we've cached the result for i in mem.</strong>
        }
        mem[i] = res;
        return res;
    }
};

  

posted @   JTechRoad  阅读(144)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示