Leetcode-802

Find Eventual Safe States

 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
#include <iostream>
#include <vector>

const int UNVISITED = 0;
const int VISITED = 1;
const int SAFE = 2;

class Solution {
    bool DFS(int i, std::vector<int>& state, std::vector<std::vector<int>>& graph) {
        if (state[i] != UNVISITED) {
            return state[i] == SAFE;
        }
        state[i] = VISITED;
        for (auto j : graph[i]) {
            if (!DFS(j, state, graph)) {
                return false;
            }
        }
        state[i] = SAFE;
        return true;
    }
        
public:
    std::vector<int> eventualSafeNodes(std::vector<std::vector<int>>& graph) {
        int n = graph.size();
        std::vector<int> state(n, UNVISITED);
        std::vector<int> res;
        res.reserve(n);
        for (int i = 0; i < n; ++i) {
            if (DFS(i, state, graph)) {
                res.push_back(i);
            }
        }
        return res;
    }
};

Leetcode-802

Licensed under CC BY-NC-SA 4.0