[LeetCode] Course Schedule II
Well, this problem is spiritually similar to to Course Schedule. You only need to store the nodes in the order you visit into a vector during BFS or DFS. Well, for DFS, a final reversal is required.
BFS
1 class Solution { 2 public: 3 vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { 4 vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites); 5 vector<int> degrees = compute_indegree(graph); 6 queue<int> zeros; 7 for (int i = 0; i < numCourses; i++) 8 if (!degrees[i]) zeros.push(i); 9 vector<int> toposort; 10 for (int i = 0; i < numCourses; i++) { 11 if (zeros.empty()) return {}; 12 int zero = zeros.front(); 13 zeros.pop(); 14 toposort.push_back(zero); 15 for (int neigh : graph[zero]) { 16 if (!--degrees[neigh]) 17 zeros.push(neigh); 18 } 19 } 20 return toposort; 21 } 22 private: 23 vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) { 24 vector<unordered_set<int>> graph(numCourses); 25 for (auto pre : prerequisites) 26 graph[pre.second].insert(pre.first); 27 return graph; 28 } 29 vector<int> compute_indegree(vector<unordered_set<int>>& graph) { 30 vector<int> degrees(graph.size(), 0); 31 for (auto neighbors : graph) 32 for (int neigh : neighbors) 33 degrees[neigh]++; 34 return degrees; 35 } 36 };
DFS
1 class Solution { 2 public: 3 vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { 4 vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites); 5 vector<int> toposort; 6 vector<bool> onpath(numCourses, false), visited(numCourses, false); 7 for (int i = 0; i < numCourses; i++) 8 if (!visited[i] && dfs(graph, i, onpath, visited, toposort)) 9 return {}; 10 reverse(toposort.begin(), toposort.end()); 11 return toposort; 12 } 13 private: 14 vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) { 15 vector<unordered_set<int>> graph(numCourses); 16 for (auto pre : prerequisites) 17 graph[pre.second].insert(pre.first); 18 return graph; 19 } 20 bool dfs(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited, vector<int>& toposort) { 21 if (visited[node]) return false; 22 onpath[node] = visited[node] = true; 23 for (int neigh : graph[node]) 24 if (onpath[neigh] || dfs(graph, neigh, onpath, visited, toposort)) 25 return true; 26 toposort.push_back(node); 27 return onpath[node] = false; 28 } 29 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· 程序员常用高效实用工具推荐,办公效率提升利器!
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 【译】WinForms:分析一下(我用 Visual Basic 写的)