802. Find Eventual Safe States

my answer:

class Solution {
    bool DFS(int v, set<int> &s, vector<vector<int>>& g, vector<int> &a) {
        int u = -1;
        for (int i = 0; i < g[v].size(); i++) {
            u = g[v][i];
            if ((a[u] == 1) || (s.find(u) != s.end())) {
                set<int>::iterator it;
                a[v] = 1; 
                return true;
            } else if (a[u] == -1) {
                s.insert(u);
                if (DFS(u, s, g, a)) {
                    a[v] = 1;
                    return true;
                }
                s.erase(u);
            }
        }
        a[v] = 0;
        return false;
    }
public:
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        queue<int> empty;
        vector<int> r;
        vector<int> a(graph.size(), -1);
        set<int> s;
        for (int i = 0; i < graph.size(); i++) {
            if (a[i] != -1)
                continue;
            DFS(i, s, graph, a);
        }
        for (int i = 0; i < a.size(); i++) {
            if (a[i] == 0) {
                r.push_back(i);
            }
        }    
        return r;
    }
};

留言

這個網誌中的熱門文章

https://leetcode.com/contest/leetcode-weekly-contest-52/problems/longest-univalue-path/

https://leetcode.com/contest/leetcode-weekly-contest-52/problems/maximum-sum-of-3-non-overlapping-subarrays/