码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 802. Find Eventual Safe States

时间:2021-05-24 09:15:19      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:init   insert   tor   for   div   graph   tmp   stat   索引   

 

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;
    }
};

 

leetcode 802. Find Eventual Safe States

标签:init   insert   tor   for   div   graph   tmp   stat   索引   

原文地址:https://www.cnblogs.com/Babylon/p/14768589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!