Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created May 10, 2018 14:04
Show Gist options
  • Save s4553711/68c2d1af8ce3a62d20822c291776d413 to your computer and use it in GitHub Desktop.
Save s4553711/68c2d1af8ce3a62d20822c291776d413 to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
vector<State> states(graph.size(), UNKNOWN);
vector<int> ans;
for(int i = 0; i < graph.size(); i++) {
if (dfs(graph, i, states) == SAFE) {
ans.push_back(i);
}
}
return ans;
}
private:
enum State {UNKNOWN, VISITING, SAFE, UNSAFE};
State dfs(const vector<vector<int>>& g, int curr, vector<State>& states) {
if (states[curr] == VISITING) {
return states[curr] = UNSAFE;
}
if (states[curr] != UNKNOWN) {
return states[curr];
}
states[curr] = VISITING;
for (int next : g[curr]) {
if (dfs(g, next, states) == UNSAFE)
return states[curr] = UNSAFE;
}
return states[curr] = SAFE;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment