标签:
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; } };
标签:
原文地址:http://www.cnblogs.com/tonix/p/4504927.html