Created
May 10, 2018 14:04
-
-
Save s4553711/68c2d1af8ce3a62d20822c291776d413 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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