207. Course Schedule

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, is it possible for you to finish all courses?

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 it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.

Topological Sort: http://www.jianshu.com/p/5880cf3be264

Solution1:Topological sort from Indegree==0 (by BFS)

思路:从indegree==0的地方bfs向内部找,找到将该node剪掉(其置为visited或将其indegree无效 并 更新其neighbors的indegree--),然后继续从indegree==0的地方找。当找不到的时候退出,看是否遍历了全部N个结点。
(queue也可以该成stack, 但整体思路是BFS的,内部小部分dfs/bfs都可以)
(不用queue起始也可以的,hashmap记录indegree==0的标号,或是每次再搜索别的indegree==0的结点,整体思路是BFS的)
BFS uses the indegrees of each node. We will first try to find a node with 0 indegree. If we fail to do so, there must be a cycle in the graph and we return false. Otherwise we have found one. We set its reduce the indegrees of all its neighbors by 1. This process should be repeated for n (number of nodes) times. If not, we return false, otherwise we will return true.
实现1a: 邻接矩阵
Time Complexity: O(V ^ 2) Space Complexity: O(V ^ 2)
实现1b: 邻接表 (recommended)
Time Complexity: O(V + E) Space Complexity: O(V + E)

Solution2:Topological sort (DFS) 看是否onpath上有cycle

思路:任意起始dfs向深找,过程记录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.

If it meets a node which was visited in the current process of DFS visit, a cycle is detected and we will return false. Otherwise it will start from another unvisited node and repeat this process till all the nodes have been visited. Note that you should make two records: one is to record all the visited nodes and the other is to record the visited nodes in the current DFS visit.

这里实现用了 邻接表
Time Complexity: O(V + E) Space Complexity: O(V + E) 递归缓存

Solution1a Code:

class Solution {
   public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[][] matrix = new int[numCourses][numCourses]; // i -> j
        int[] indegree = new int[numCourses];

        // graph build
        for (int i = 0; i < prerequisites.length; i++) {
            int pre = prerequisites[i][1];
            int post = prerequisites[i][0];
            indegree[post]++; 
            matrix[pre][post] = 1;
        }

        // bfs from nodes whose degree == 0
        int count = 0;
        Queue<Integer> queue = new LinkedList();
        for (int i = 0; i < indegree.length; i++) {
            if (indegree[i] == 0) queue.offer(i);
        }
        while (!queue.isEmpty()) {
            int course = queue.poll();
            count++;
            for (int i = 0; i < numCourses; i++) {
                if (matrix[course][i] != 0) {
                    if (--indegree[i] == 0)
                        queue.offer(i);
                }
            }
        }
        return count == numCourses;
    }
}

Solution1b Code:

class Solution {
   public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] indegree = new int[numCourses];
        // O(V + E)
        // graph build
        // graph = adj_list init
        List<List<Integer>> graph = new ArrayList<List<Integer>>();
        for(int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<Integer>()); // LinkedList is also OK
        }
       // O(E) part
        for (int i = 0; i < prerequisites.length; i++) {
            int pre = prerequisites[i][1];
            int post = prerequisites[i][0];
            indegree[post]++; 
            graph.get(pre).add(post);
        }
        // O(V) part
        // bfs from nodes whose degree == 0
        int count = 0;
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < indegree.length; i++) {
            if (indegree[i] == 0) queue.offer(i);
        }
        while (!queue.isEmpty()) {
            int course = queue.poll();
            count++;
            List<Integer> next_list = graph.get(course);
            for(int i = 0; i < next_list.size(); i++) {
                if (--indegree[next_list.get(i)] == 0) {
                    queue.offer(next_list.get(i));
                }
            }
           
        }
        return count == numCourses;
    }
}

Solution2 Code:

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        // O(V + E)
        // graph = adj_list init
        List<List<Integer>> graph = new ArrayList<List<Integer>>();
        for(int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<Integer>()); // LinkedList is also OK
        }
        
        boolean[] visited = new boolean[numCourses];
        boolean[] onpath = new boolean[numCourses];
        // O(E) part
        // graph(adj_list) build
        for (int i = 0; i < prerequisites.length; i++) {
            int pre = prerequisites[i][1];
            int post = prerequisites[i][0];
            graph.get(pre).add(post);
        }
       // O(V) part
        for(int i = 0; i < numCourses; i++) {
            if(!visited[i] && dfs_cycle(graph, i, visited, onpath)) {
                return false;
            }
        }
                
        return true;
    }
    
    // dfs to detect cycle by using onpath, if detected: return true;
    private boolean dfs_cycle(List<List<Integer>> graph, int node, boolean[] visited, boolean[] onpath) {

        onpath[node] = true;
        visited[node] = true; 
        
        for(int i = 0; i < graph.get(node).size(); i++) {
            int neighbor = graph.get(node).get(i);
            if (onpath[neighbor] || (!visited[neighbor] && dfs_cycle(graph, neighbor, visited, onpath))) {
                return true;
            }
        }
        // onpath step back
        onpath[node] = false;
        
        return false;       
    }
}

Solution2.round1 Code:

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if(numCourses == 0 || prerequisites == null || prerequisites.length == 0) return true;
        
        // graph define
        List<List<Integer>> graph = new ArrayList<>();
        for(int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<>());
        }
        
        // graph build
        for(int i = 0; i < prerequisites.length; i++) {
            graph.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }
        
        boolean[] g_visited = new boolean[numCourses];
        boolean[] on_path = new boolean[numCourses];
        
        
        for(int i = 0; i < numCourses; i++) {
            if(!g_visited[i] && dfsDetectCycle(graph, i, g_visited, on_path)) {
                return false;
            }
        }
        
        return true;
        
        
    }
    
    private boolean dfsDetectCycle(List<List<Integer>> graph, int cur, boolean[] g_visited, boolean[] on_path) {
        
        g_visited[cur] = true;
        on_path[cur] = true;
        
        List<Integer> neighbors = graph.get(cur);
        for(Integer neighbor: neighbors) {
            if(on_path[neighbor]) {
                return true;
            }
            
            if(g_visited[neighbor]) continue;
            if(dfsDetectCycle(graph, neighbor, g_visited, on_path)) {
                return true;
            }
        }
        on_path[cur] = false;
        
        return false;
    }
}

Tag_Round1 Code

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        
        if(numCourses == 0 || prerequisites == null || prerequisites.length == 0) return true;
        
        // build graph
        List<List<Integer>> graph = new ArrayList<>();
        for(int i = 0; i< numCourses; i++) {
            graph.add(new ArrayList<>());
        }
        
        // init graph 
        for(int i = 0; i < prerequisites.length; i++) {
            int pre = prerequisites[i][1];
            int post = prerequisites[i][0];
            graph.get(pre).add(post);
        }
        
        boolean[] g_visited = new boolean[numCourses];
        boolean[] on_path = new boolean[numCourses];
        
        // dfs detect cycle
        for(int i = 0; i < graph.size(); i++) {
            if(g_visited[i] || graph.get(i).size() == 0) continue;
            if(dfsCycle(graph, i, g_visited, on_path)) {
                return false;
            }
        }
        return true;
        
    }
    
    private boolean dfsCycle(List<List<Integer>> graph, int start_id, boolean[] g_visited, boolean[] on_path) {
        g_visited[start_id] = true;
        on_path[start_id] = true;
        
        List<Integer> next_list = graph.get(start_id);
        for(int i = 0; i < next_list.size(); i++) {
            int next = next_list.get(i);
            if(on_path[next]) return true;
            if(g_visited[next]) continue;
            if(dfsCycle(graph, next, g_visited, on_path)) return true;
         
        }
        on_path[start_id] = false;
        return false;
    }
}

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

推荐阅读更多精彩内容