/** 207. Course Schedule * 2016-3-28 by Jyuan * BFS: A typical topological sort. The principle is also very simple, in a directed graph, each time to find a node without a precursor node (that is, the node in the degree of 0), * and then point it to the other nodes are removed, repeat the process (BFS) until all the nodes have been found, or there are no eligible nodes (if there is a ring in the diagram). * DFS solution, also need to establish a map, or use a two-dimensional array to build, and BFS, and we need a one-dimensional array visit to record the access status, * The general idea is to set up a good map, and then start from the first course, to find out which course it can constitute, Temporarily marks the current course as accessed, * and then calls DFS recursion on the newly obtained course until a new course has been visited, returns false, returns True if no conflict is present, and then changes the course marked as visited to not accessed *http://www.jyuan92.com/blog/leetcode-course-schedule/ */ Public BooleanCanfinish (intNumcourses,int[] Prerequisites) { if(NULL= = Prerequisites | | Numcourses = = 0 | | Prerequisites.length = = 0) { return true; } int[] precourses =New int[numcourses]; //Store the In-degree # for(int[] prerequisite:prerequisites) {precourses[prerequisite[0]]++; } Queue<Integer> queue =NewLinkedlist<integer>(); for(inti = 0; i < precourses.length; i++) { if(Precourses[i] = = 0) {queue.add (i); } } intNumofprecourse = 0; while(!Queue.isempty ()) { inttop =Queue.poll (); Numofprecourse++; for(int[] prerequisite:prerequisites) { if(prerequisite[1] = = top) {//find every post-courseprecourses[prerequisite[0]]--; if(Precourses[prerequisite[0]] = = 0) {Queue.add (prerequisite[0]); } } } } returnNumofprecourse = =numcourses; }
207. Course Schedule