[LintCode] Course Schedule II

本文详细介绍了如何使用两种不同的算法——宽度优先搜索(BFS)和深度优先搜索(DFS)来解决课程排序问题。通过实例展示了当存在课程先修条件时,如何确定完成所有课程的有效顺序。并提供了完整的代码实现。

There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example

Given n = 2, prerequisites = [[1,0]]
Return [0,1]

Given n = 4, prerequisites = [1,0],[2,0],[3,1],[3,2]]
Return [0,1,2,3] or [0,2,1,3]

 
This problem is essentially the same with Course Schedule. The only difference is that this problem asks for a concrete topological ordering.
We can leverage the solutions from Topological Sorting and solve this problem using both BFS and DFS. The difference here would be cycle detection logic since it is not guranteed that we can find a topological ordering.
 
Solution 1. BFS 
 1 public class Solution {
 2     /**
 3      * @param numCourses a total of n courses
 4      * @param prerequisites a list of prerequisite pairs
 5      * @return the course order
 6      */
 7     public int[] findOrder(int numCourses, int[][] prerequisites) {
 8         ArrayList<ArrayList<Integer>> edges = new ArrayList<ArrayList<Integer>>();
 9         int[] incomingEdgeNum = new int[numCourses];
10         int[] result = new int[numCourses];
11         
12         for(int i = 0; i < numCourses; i++)
13         {
14             edges.add(new ArrayList<Integer>());
15         }
16         int courseNum;
17         for(int i = 0; i < prerequisites.length; i++)
18         {
19             courseNum = prerequisites[i][0];
20             incomingEdgeNum[courseNum]++;
21             edges.get(prerequisites[i][1]).add(courseNum);
22         }
23         
24         Queue<Integer> queue = new LinkedList<Integer>();
25         int currIdx = 0;
26         for(int i = 0; i < incomingEdgeNum.length; i++)
27         {
28             if(incomingEdgeNum[i] == 0)
29             {
30                 queue.add(i);
31                 result[currIdx] = i;
32                 currIdx++;
33             }
34         }
35         
36         int count = 0;
37         while(!queue.isEmpty())
38         {
39             int course = queue.poll();
40             count++;
41             int n = edges.get(course).size();
42             for(int i = 0; i < n; i++)
43             {
44                 int neighbor = edges.get(course).get(i);
45                 incomingEdgeNum[neighbor]--;
46                 if(incomingEdgeNum[neighbor] == 0)
47                 {
48                     queue.add(neighbor);
49                     result[currIdx] = neighbor;
50                     currIdx++;
51                 }
52             }
53         }
54         if(count < numCourses)
55         {
56             return new int[0];
57         }
58         return result;
59     }
60 }

 

Solution 2.DFS 
The depth of the recursive calls can get big if the input size gets big.
 
 1 public class Solution {
 2     public int[] findOrder(int numCourses, int[][] prerequisites) {
 3         if(numCourses <= 0) {
 4             return new int[0];
 5         }
 6         if(prerequisites == null) {
 7             int[] result = new int[numCourses];
 8             for(int i = 0; i < numCourses; i++) {
 9                 result[i] = i;
10             }
11             return result;
12         }
13         ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
14         for(int i = 0; i < numCourses; i++) {
15             graph.add(new ArrayList<Integer>());
16         }
17         for(int j = 0; j < prerequisites.length; j++) {
18             graph.get(prerequisites[j][1]).add(prerequisites[j][0]);
19         }
20         boolean hasCycle = false;
21         Set<Integer> exploring = new HashSet<Integer>();
22         Set<Integer> explored = new HashSet<Integer>();
23         Stack<Integer> stack = new Stack<Integer>();
24         int[] result = new int[numCourses];
25         for(int i = 0; i < numCourses; i++) {
26             if(!explored.contains(i) && dfs(i, exploring, explored, graph, stack)) {
27                 hasCycle = true;
28                 break;
29             }
30         }
31         if(hasCycle) {
32             return new int[0];
33         }
34         int idx = 0;
35         while(!stack.empty()) {
36             result[idx] = stack.pop();
37             idx++;
38         }
39         return result;
40     }
41     private boolean dfs(int current, Set<Integer> exploring, Set<Integer> explored,
42                         ArrayList<ArrayList<Integer>> graph, Stack<Integer> stack) {
43         exploring.add(current);
44         for(Integer neighbor : graph.get(current)) {
45             if(explored.contains(neighbor)) {
46                 continue;
47             }
48             if(exploring.contains(neighbor)) {
49                 return true;
50             }
51             if(dfs(neighbor, exploring, explored, graph, stack)) {
52                 return true;
53             }
54         }
55         exploring.remove(current);
56         explored.add(current);
57         stack.push(current);
58         return false;
59     } 
60 }

 

 
Related Problems
Course Schedule
Sequence Reconstruction
Topological Sorting
 

转载于:https://www.cnblogs.com/lz87/p/7493993.html

根据原作 https://pan.quark.cn/s/459657bcfd45 的源码改编 Classic-ML-Methods-Algo 引言 建立这个项目,是为了梳理和总结传统机器学习(Machine Learning)方法(methods)或者算法(algo),和各位同仁相互学习交流. 现在的深度学习本质上来自于传统的神经网络模型,很大程度上是传统机器学习的延续,同时也在不少时候需要结合传统方法来实现. 任何机器学习方法基本的流程结构都是通用的;使用的评价方法也基本通用;使用的一些数学知识也是通用的. 本文在梳理传统机器学习方法算法的同时也会顺便补充这些流程,数学上的知识以供参考. 机器学习 机器学习是人工智能(Artificial Intelligence)的一个分支,也是实现人工智能最重要的手段.区别于传统的基于规则(rule-based)的算法,机器学习可以从数据中获取知识,从而实现规定的任务[Ian Goodfellow and Yoshua Bengio and Aaron Courville的Deep Learning].这些知识可以分为四种: 总结(summarization) 预测(prediction) 估计(estimation) 假想验证(hypothesis testing) 机器学习主要关心的是预测[Varian在Big Data : New Tricks for Econometrics],预测的可以是连续性的输出变量,分类,聚类或者物品之间的有趣关联. 机器学习分类 根据数据配置(setting,是否有标签,可以是连续的也可以是离散的)和任务目标,我们可以将机器学习方法分为四种: 无监督(unsupervised) 训练数据没有给定...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值