BFS:
1 /** 2 * Definition for Directed graph. 3 * struct DirectedGraphNode { 4 * int label; 5 * vector<DirectedGraphNode *> neighbors; 6 * DirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution { 10 public: 11 /** 12 * @param graph: A list of Directed graph node 13 * @return: Any topological order for the given graph. 14 */ 15 vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) { 16 // write your code here 17 vector<DirectedGraphNode*> topo; 18 unordered_map<DirectedGraphNode*, int> degrees = compute_indegree(graph); 19 queue<DirectedGraphNode*> zeros; 20 for (auto itr = degrees.begin(); itr != degrees.end(); itr++) 21 if ((*itr).second == 0) 22 zeros.push((*itr).first); 23 while (!zeros.empty()) { 24 DirectedGraphNode* zero = zeros.front(); 25 zeros.pop(); 26 topo.push_back(zero); 27 for (DirectedGraphNode* neigh : zero -> neighbors) 28 if (--degrees[neigh] == 0) 29 zeros.push(neigh); 30 } 31 return topo; 32 } 33 private: 34 unordered_map<DirectedGraphNode*, int> compute_indegree(vector<DirectedGraphNode*>& graph) { 35 unordered_map<DirectedGraphNode*, int> degrees; 36 for (DirectedGraphNode* node : graph) { 37 if (degrees.find(node) == degrees.end()) 38 degrees[node] = 0; 39 for (DirectedGraphNode* neigh : node -> neighbors) 40 degrees[neigh]++; 41 } 42 return degrees; 43 } 44 };
DFS:
1 /** 2 * Definition for Directed graph. 3 * struct DirectedGraphNode { 4 * int label; 5 * vector<DirectedGraphNode *> neighbors; 6 * DirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution { 10 public: 11 /** 12 * @param graph: A list of Directed graph node 13 * @return: Any topological order for the given graph. 14 */ 15 vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) { 16 // write your code here 17 vector<DirectedGraphNode*> topo; 18 unordered_set<DirectedGraphNode*> visited; 19 for (DirectedGraphNode* node : graph) 20 if (visited.find(node) == visited.end()) 21 dfs(graph, node, visited, topo); 22 reverse(topo.begin(), topo.end()); 23 return topo; 24 } 25 private: 26 void dfs(vector<DirectedGraphNode*>& graph, DirectedGraphNode* node, 27 unordered_set<DirectedGraphNode*>& visited, 28 vector<DirectedGraphNode*>& topo) { 29 visited.insert(node); 30 for (DirectedGraphNode* neigh : node -> neighbors) 31 if (visited.find(neigh) == visited.end()) 32 dfs(graph, neigh, visited, topo); 33 topo.push_back(node); 34 } 35 };
时间: 2024-12-26 01:28:55