您的位置:首页 > 其它

LeetCode "Course Schedule II"

2015-05-15 02:46 363 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: