210. Course Schedule II

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所示

屏幕快照 2017-09-21 下午4.49.50.png

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,158评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,600评论 1 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,785评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,655评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,075评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,002评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,146评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,918评论 0 211
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,671评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,838评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,318评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,636评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,343评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,187评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,982评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,126评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,934评论 2 279

推荐阅读更多精彩内容