博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] 拓扑排序
阅读量:5995 次
发布时间:2019-06-20

本文共 2496 字,大约阅读时间需要 8 分钟。

BFS:

1 /** 2  * Definition for Directed graph. 3  * struct DirectedGraphNode { 4  *     int label; 5  *     vector
neighbors; 6 * DirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution {10 public:11 /**12 * @param graph: A list of Directed graph node13 * @return: Any topological order for the given graph.14 */15 vector
topSort(vector
graph) {16 // write your code here17 vector
topo;18 unordered_map
degrees = compute_indegree(graph);19 queue
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
compute_indegree(vector
& graph) {35 unordered_map
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
neighbors; 6 * DirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution {10 public:11 /**12 * @param graph: A list of Directed graph node13 * @return: Any topological order for the given graph.14 */15 vector
topSort(vector
graph) {16 // write your code here17 vector
topo;18 unordered_set
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
& graph, DirectedGraphNode* node, 27 unordered_set
& visited, 28 vector
& 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 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4606310.html

你可能感兴趣的文章
Android——TabHost(标签容器)相关知识总结贴
查看>>
process launch failed : failed to get the task for process xxx
查看>>
[转]12篇学通C#网络编程——第二篇 HTTP应用编程(上)
查看>>
索引实战
查看>>
ADS1.2安装
查看>>
[华为机试练习题]9.坐标移动
查看>>
April Fools Day Contest 2016 B. Scrambled
查看>>
iOS开发--多线程
查看>>
BZOJ4527 : K-D-Sequence
查看>>
网易游戏2015年暑期实习生面试经历-游戏研发project师
查看>>
Celery的实践指南
查看>>
Shell中的while循环【转】
查看>>
Linux下安装memcached
查看>>
HoloLens开发手记 - 入门学习阶段总结
查看>>
qt介绍
查看>>
静态语句块、构造语句块以及构造函数的执行顺序
查看>>
Spring MVC @RequestMapping注解详解
查看>>
[javaEE] 三层架构案例-用户模块(一)
查看>>
思维导图——项目计划
查看>>
IOS基础之UILineBreakModeWordWrap
查看>>