1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include "graph.hpp" #include <list> #include <stdlib.h> #include <crtdbg.h>
vector<vector<Node *>> sortedTopology(Graph *graph) { unordered_map<Node *, int> inMap; queue<Node *> zeroInQue; for (auto &node : graph->nodes) { inMap[node.second.get()] = node.second.get()->in; if (node.second.get()->in == 0) { zeroInQue.push(node.second.get()); } }
int count1 = 0, count2 = 0; vector<vector<Node *>> result; while (!zeroInQue.empty()) { int size = zeroInQue.size(); result.push_back(vector<Node*>()); while (size--) { Node *cur = zeroInQue.front(); zeroInQue.pop(); result[count1].push_back(cur); count2++; for(auto & next : cur->nexts) { if(--inMap[next] == 0) { zeroInQue.push(next); } } } count1++; }
if (count2 != graph->nodes.size()) { cout << "There is a cyclic dependency" << endl; } return result; }
void test1() { vector<vector<int>> matrix = {{1, 1, 2}, {1, 2, 3}, {1, 3, 4}, {1, 1, 5}, {1, 1, 3}, {1, 4, 2}};
shared_ptr<Graph> graph = creatGraph(matrix); vector<vector<Node *>> res = sortedTopology(graph.get()); }
int main() { test1(); _CrtDumpMemoryLeaks();
return 0; }
|