|
| 1 | +/* |
| 2 | +* Author: illuz <iilluzen[at]gmail.com> |
| 3 | +* File: AC_dfs_n.cpp |
| 4 | +* Create Date: 2016-02-27 12:00:45 |
| 5 | +* Descripton: |
| 6 | +*/ |
| 7 | + |
| 8 | +#include <bits/stdc++.h> |
| 9 | + |
| 10 | +using namespace std; |
| 11 | +const int N = 0; |
| 12 | + |
| 13 | +class Solution { |
| 14 | +public: |
| 15 | + vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { |
| 16 | + graph = vector<vector<int> >(numCourses); |
| 17 | + vis = vector<int>(numCourses); |
| 18 | + |
| 19 | + vector<int> inorder(numCourses); |
| 20 | + vector<int> path; |
| 21 | + // generate the tree map |
| 22 | + for (auto prerequisite : prerequisites) { |
| 23 | + graph[prerequisite.second].push_back(prerequisite.first); |
| 24 | + inorder[prerequisite.first] += 1; |
| 25 | + } |
| 26 | + // find out 0-in-order node and dfs |
| 27 | + for (int i = 0; i < numCourses; ++i) { |
| 28 | + if (inorder[i] == 0) { |
| 29 | + if (dfs(i, path) == false) // can not topsort |
| 30 | + return vector<int>(); |
| 31 | + } |
| 32 | + } |
| 33 | + if (path.size() != numCourses) |
| 34 | + return vector<int>(); |
| 35 | + reverse(path.begin(), path.end()); |
| 36 | + return path; |
| 37 | + } |
| 38 | +private: |
| 39 | + vector<vector<int> > graph; |
| 40 | + vector<int> vis; |
| 41 | + |
| 42 | + bool dfs(int id, vector<int> &path) { |
| 43 | + vis[id] = 1; // visiting |
| 44 | + for (auto toid : graph[id]) { |
| 45 | + if (vis[toid] == 1) |
| 46 | + return false; |
| 47 | + if (vis[toid] == 2) |
| 48 | + continue; |
| 49 | + if (dfs(toid, path) == false) |
| 50 | + return false; |
| 51 | + } |
| 52 | + vis[id] = 2; // visited |
| 53 | + path.push_back(id); |
| 54 | + return true; |
| 55 | + } |
| 56 | +}; |
| 57 | + |
| 58 | +int main() { |
| 59 | + Solution s; |
| 60 | + vector<pair<int, int>> prerequisites; |
| 61 | + prerequisites.push_back(pair<int, int>(0, 2)); |
| 62 | + prerequisites.push_back(pair<int, int>(2, 0)); |
| 63 | + prerequisites.push_back(pair<int, int>(1, 2)); |
| 64 | + vector<int> res = s.findOrder(3, prerequisites); |
| 65 | + for (auto x : res) cout << x << ' '; |
| 66 | + return 0; |
| 67 | +} |
| 68 | + |
0 commit comments