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.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
思路/实现 参考 207. Course Schedule http://www.jianshu.com/p/8665248b4458
基本相同,加上过程中返回reesult_order
Solution1:Topological Sort from Indegree==0 (by BFS)
思路:从indegree==0的地方bfs向内部找,找到将该node剪掉(其置为visited或将其indegree无效 并 更新其neighbors的indegree--),然后继续从indegree==0的地方找,过程中保存res_order作结果, 当找不到的时候退出,看是否遍历了全部N个结点,如果是说明能够课程能够正常finish,不存在loop,返回res_order。
(queue也可以该成stack, 但整体思路是BFS的,内部小部分dfs/bfs都可以)
(不用queue其实也可以的,hashmap记录indegree==0的标号,或是每次再搜索别的indegree==0的结点,整体思路是BFS的)
实现: 图的表示:邻接表
Time Complexity: O(V + E) Space Complexity: O(V + E)
Solution2:Topological sort (DFS)
思路:
参考:http://www.jianshu.com/p/5880cf3be264
参考: https://www.youtube.com/watch?v=n_yl2a6n7nM
任意起始 dfs向深找,找到最深一个元素,标为N(或放入stack),backwards标记N -1, N-2..(或放入stack),直到某个结点有别的路先不标这个点 先走别的路到底往回 继续标(或放入stack)。过程记录global visited,global visited的说明已经dfs过了不用处理,其实还应该keep一个on_path的visited,就是一次dfs到底过程中的on_path visited,如果碰到on_path visited 说明有loop不能够完成Topological Sort。on_path visited的更新类似回溯,到底后回溯回来一步要将该结点的on_path visited再改为false.
**2_b: **或者不用stack,用linkedlist:直接放入insert到linkedlist前部,其实在这里和stack的作用是一样,如solution2b所示
Note: order_result不通过放入stack的方式也可以,已知结点数,直接int order_result[N],dfs到底最后一个标为N即放入order_result[N-1]的位置,依次N-1backwards回标放入。参数传递需要"放入位置";还没有实现
实现: 图的表示:邻接表
Time Complexity: O(V + E) Space Complexity: O(V + E)
Solution1 Code:
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
List<List<Integer>> graph = new ArrayList<List<Integer>>(); // graph = adj_list
initialiseGraph(indegree, graph, prerequisites);
return solveByBFS(indegree, graph);
//return solveByDFS(graph);
}
private void initialiseGraph(int[] indegree, List<List<Integer>> graph, int[][] prerequisites) {
int n = indegree.length;
for(int i = 0; i < n; i++) {
graph.add(new ArrayList<Integer>()); // LinkedList is also OK
}
for (int[] edge: prerequisites) {
indegree[edge[0]]++;
graph.get(edge[1]).add(edge[0]);
}
}
private int[] solveByBFS(int[] indegree, List<List<Integer>> graph){
int n = indegree.length;
int[] res_order = new int[n];
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < indegree.length; i++) {
if (indegree[i] == 0) queue.offer(i);
}
int visited_count = 0;
while (!queue.isEmpty()) {
int from = queue.poll();
res_order[visited_count++] = from;
for (int next_course : graph.get(from)) {
indegree[next_course]--;
if (indegree[next_course] == 0) {
queue.offer(next_course);
}
}
}
return visited_count == n ? res_order : new int[0];
}
}
Solution2a Code:
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
List<List<Integer>> graph = new ArrayList<List<Integer>>(); // graph = adj_list
initialiseGraph(indegree, graph, prerequisites);
//return solveByBFS(indegree, graph);
return solveByDFS(graph);
}
private void initialiseGraph(int[] indegree, List<List<Integer>> graph, int[][] prerequisites) {
int n = indegree.length;
for(int i = 0; i < n; i++) {
graph.add(new ArrayList<Integer>()); // LinkedList is also OK
}
for (int[] edge: prerequisites) {
indegree[edge[0]]++;
graph.get(edge[1]).add(edge[0]);
}
}
private int[] solveByDFS(List<List<Integer>> graph) {
BitSet hasCycle = new BitSet(1);
boolean[] visited = new boolean[graph.size()];
boolean[] on_path = new boolean[graph.size()];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < graph.size(); i++) {
if (!visited[i] && dfs(graph, i, visited, on_path, stack) == false) {
return new int[0];
}
}
int[] res_order = new int[graph.size()];
for (int i = 0; !stack.isEmpty(); i++) res_order[i] = stack.pop();
return res_order;
}
// dfs to detect path order, if detect cycle: return false;
private boolean dfs(List<List<Integer>> graph, int from, boolean[] visited, boolean[] on_path, Deque<Integer> stack) {
visited[from] = true;
on_path[from] = true;
for (int to : graph.get(from)) {
// if(on_path[to] == true) return false;
// if(!visited[to] && !dfs(graph, to, visited, on_path, stack)) return false;
if (!visited[to]) {
if(!dfs(graph, to, visited, on_path, stack)) {
return false;
}
} else if (on_path[to] == true) {
return false;
}
}
on_path[from] = false;
stack.push(from);
return true;
}
}
Solution2b Code:
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
List<List<Integer>> graph = new ArrayList<List<Integer>>(); // graph = adj_list
initialiseGraph(indegree, graph, prerequisites);
//return solveByBFS(indegree, graph);
return solveByDFS(graph);
}
private void initialiseGraph(int[] indegree, List<List<Integer>> graph, int[][] prerequisites) {
int n = indegree.length;
for(int i = 0; i < n; i++) {
graph.add(new ArrayList<Integer>()); // LinkedList is also OK
}
for (int[] edge: prerequisites) {
indegree[edge[0]]++;
graph.get(edge[1]).add(edge[0]);
}
}
private int[] solveByDFS(List<List<Integer>> graph) {
BitSet hasCycle = new BitSet(1);
boolean[] visited = new boolean[graph.size()];
boolean[] on_path = new boolean[graph.size()];
List<Integer> route = new LinkedList<>();
for (int i = 0; i < graph.size(); i++) {
if (!visited[i] && dfs(graph, i, visited, on_path, route) == false) {
return new int[0];
}
}
// prepare the result
int[] res_order = new int[graph.size()];
ListIterator<Integer> iter = route.listIterator();
int i = 0;
while (iter.hasNext()) {
res_order[i++] = iter.next();
}
return res_order;
}
// dfs to detect path order, if detect cycle: return false;
private boolean dfs(List<List<Integer>> graph, int from, boolean[] visited, boolean[] on_path, List<Integer> route) {
visited[from] = true;
on_path[from] = true;
for (int to : graph.get(from)) {
// if(on_path[to] == true) return false;
// if(!visited[to] && !dfs(graph, to, visited, on_path, stack)) return false;
if (!visited[to]) {
if(!dfs(graph, to, visited, on_path, route)) {
return false;
}
} else if (on_path[to] == true) {
return false;
}
}
on_path[from] = false;
route.add(0, from);
return true;
}
}