leetcode 802. Find Eventual Safe States
1.出度为0则为满足条件的节点,取所有出度为0的到queue中,之后循环减去这些队列中的出度,正反索引减少访问时间
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { vector<int> ret; int n=graph.size(); vector<int> for_graph(n); //forward and reverse index vector<unordered_set<int>> rev_graph(n, unordered_set<int>()); //priority_queue<int,vector<int>,greater<int>> min_q; queue<int> q; //initialize for(int i=0;i<n;++i){ if(graph[i].empty()){ q.push(i); //min_q.push(i); }else{ for (int j : graph[i]) { ++for_graph[i]; rev_graph[j].insert(i); } } } while(!q.empty()){ int tmp=q.front(); q.pop(); for(int for_idx:rev_graph[tmp]){ --for_graph[for_idx]; if(for_graph[for_idx]==0){ q.push(for_idx); //min_q.push(for_idx); } } } //while(!min_q.empty()){ // //cout<<min_q.top()<<endl; // ret.push_back(min_q.top()); // min_q.pop(); //} for(int i=0;i<n;++i){ if(for_graph[i]==0)ret.push_back(i); } return ret; } };
2.dfs检测每个节点的neighor中是否有环
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { vector<int> ret; int n=graph.size(); vector<int> safe(n); for(int i=0;i<n;++i){ if(dfs(graph,i,safe))ret.push_back(i); } return ret; } bool dfs(vector<vector<int>>& graph,int idx,vector<int>& safe){ if(safe[idx]>0) return safe[idx]==2; safe[idx]=1; for(int i:graph[idx]){ if(safe[i]==2)continue; if(safe[i]==1||!dfs(graph, i, safe))return false; } safe[idx]=2; return true; } };