802. Find Eventual Safe States

In a directed graph, we start at some node and every turn, walk along a directed edge of the graph.  If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.

Now, say our starting node is  eventually safe if and only if we must eventually walk to a terminal node.  More specifically, there exists a natural number `K` so that for any choice of where to walk, we must have stopped at a terminal node in less than `K` steps.

Which nodes are eventually safe?  Return them as an array in sorted order.

The directed graph has `N` nodes with labels `0, 1, ..., N-1`, where `N` is the length of `graph`.  The graph is given in the following form: `graph[i]` is a list of labels `j` such that `(i, j)` is a directed edge of the graph.

``````Example:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.
``````

Note:

• `graph` will have length at most `10000`.
• The number of edges in the graph will not exceed `32000`.
• Each `graph[i]` will be a sorted list of different integers, chosen within the range `[0, graph.length - 1]`.

``````class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
vector<int> res;
int n = graph.size();
vector<bool> safe(n, false);
vector<set<int>> g(n, set<int>()), revg = g;
queue<int> q;
for (int i = 0; i < n; ++i) {
if (graph[i].empty()) q.push(i);
for (int j : graph[i]) {
g[i].insert(j);
revg[j].insert(i);
}
}
while (!q.empty()) {
auto t = q.front(); q.pop();
safe[t] = true;
for (int i : revg[t]) {
g[i].erase(t);
if (g[i].empty()) q.push(i);
}
}
for (int i = 0; i < n; ++i) {
if (safe[i]) res.push_back(i);
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
int n = graph.size();
vector<int> res, color(n); // 0 white, 1 gray, 2 black
for (int i = 0; i < n; ++i) {
if (helper(graph, i, color)) res.push_back(i);
}
return res;
}
bool helper(vector<vector<int>>& graph, int cur, vector<int>& color) {
if (color[cur] > 0) return color[cur] == 2;
color[cur] = 1;
for (int i : graph[cur]) {
if (color[i] == 2) continue;
if (color[i] == 1 || !helper(graph, i, color)) {
return false;
}
}
color[cur] = 2;
return true;
}
};
``````

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

https://leetcode.com/problems/find-eventual-safe-states/discuss/119871/Straightforward-Java-solution-easy-to-understand!

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation