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

LeetCode "Course Schedule II"

时间:2015-05-15 08:57:26      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

This one lets you print out one topological sorted sequence. Either BFS or DFS works. But there are tricky details.
This is my reference: https://leetcode.com/discuss/35605/two-ac-solution-in-java-using-bfs-and-dfs-with-explanation

BFS(please note the comment):

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites)
    {
        vector<int> ret;

        map<int, int> counts;
        for (int i = 0; i < numCourses; i++)
            counts.insert(make_pair(i, 0));

        map<int, vector<int>> m;
        for (auto &r : prerequisites)
        {
            m[r.second].push_back(r.first);
            counts[r.first] ++;
        }

        //    Get roots
        queue<int> q;
        for (auto &r : counts)
            if (r.second == 0)    q.push(r.first);

        while (!q.empty())
        {
            int topInx = q.front();    q.pop();
            ret.push_back(topInx);

            for (int to : m[topInx])
            {
                counts[to] --;
                //  IMPORTANT: we only put it in when all its dependents are removed
                if (counts[to] == 0) q.push(to);
            }
        }
        return ret.size() == counts.size() ? ret : vector<int>();
    }
};

DFS. We have to go backwards!

#define MAX_BIT 2000
typedef pair<int, int> Edge;
typedef map<int, vector<int>> Graph;

class Solution {
    set<int> visited;
    bitset<MAX_BIT> onstack;
    vector<int> ret;
public:
    bool go(int from, Graph &g)
    {
        visited.insert(from);
        onstack[from] = 1;
        
        for(auto to : g[from])
        {
            if(visited.find(to) == visited.end())
            {
                if (!go(to, g)) return false;
            }
            else if(onstack[to] == 1)
            {
                return false;
            }
        }

        onstack[from] = 0;
        ret.push_back(from);

        return true;
    }
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) 
    {
        //    Compse graph
        Graph adjs;
        for(auto &r : prerequisites)
        {
            adjs[r.second].push_back(r.first);
        }

        //    DFS
        for(auto &r : adjs)
        {
            if((visited.find(r.first) == visited.end()) && !go(r.first, adjs))
                return vector<int>();
        }
        //    undependent ones?
        for(int i = 0; i < numCourses; i ++)
            if (visited.find(i) == visited.end())
                ret.push_back(i);

        //
        std::reverse(ret.begin(), ret.end());
        return ret;
    }
};

LeetCode "Course Schedule II"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4504927.html

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