[LintCode] 拓扑排序
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 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 在 VS Code 中,一键安装 MCP Server!
· 千万级大表的优化技巧
· 用一种新的分类方法梳理设计模式的脉络