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.
Runtime: 268 ms, faster than 12.50% of C++ online submissions for Find Eventual Safe States.
slow
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { vector<int> indegree(graph.size(),0); vector<int> outdegree(graph.size(), 0); unordered_map<int,vector<int>> parent; for(int i=0; i<graph.size(); i++){ for(int j=0; j<graph[i].size(); j++){ indegree[graph[i][j]]++; outdegree[i]++; parent[graph[i][j]].push_back(i); } } queue<int> q; unordered_map<int,bool> used; for(int i=0; i<graph.size(); i++) used[i] = false; while(true) { for(int i=0; i<outdegree.size(); i++) { if(outdegree[i] == 0 && !used[i]) { q.push(i); } } if(q.empty()) break; while(!q.empty()) { int tmp = q.front(); q.pop(); used[tmp] = true; for(int x : parent[tmp]) { outdegree[x]--; } } } vector<int> ret; for(int i=0; i<outdegree.size(); i++){ if(outdegree[i] == 0) ret.push_back(i); } return ret; } };
Runtime: 140 ms, faster than 100.00% of C++ online submissions for Find Eventual Safe States.
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { vector<int> color(graph.size(),0); vector<int> ret; for(int i=0; i<graph.size(); i++){ if(dfs(graph, i, color)) ret.push_back(i); } return ret; } bool dfs(vector<vector<int>>& graph, int s, vector<int>& color) { if(color[s] > 0) return color[s] == 2; color[s] = 1; for(int& x : graph[s]) { if(!dfs(graph, x, color)) return false; } color[s] = 2; return true; } };