There is a total of n courses you have to take, labeled from 0 to n - 1 .
Some courses May has 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, are it possible for your to finish all courses?
For example:
2, [[1,0]]
There is a total of 2 courses to take. To take course 1 should has finished course 0. So it is possible.
2, [[1,0],[0,1]]
There is a total of 2 courses to take. To take course 1 should has finished course 0, and to take course 0 you should also has finished course 1. So it is impossible.
Public classSolution { Public BooleanCanfinish (intNumcourses,int[] Prerequisites) { //The subject is the topology map, verifying that the graph has a ring, starting from the leaf node (the point of 0), if all the points can be traversed, the condition is satisfied//An auxiliary array is required, the subscript of the array represents the course number, and the value of the array represents the degree//The queue holds a point with a degree of 0, and each time a count of counts is added to the inside, the final result is to determine if Count equals the number of courses numcourses int[]flag=New int[numcourses]; for(inti=0;i<prerequisites.length;i++) {flag[prerequisites[i][1]]++; } LinkedList<Integer> queue=NewLinkedlist<integer>(); intCount=0; for(inti=0;i<numcourses;i++){ if(flag[i]==0) {//the degree of 0Queue.add (i); Count++; } } while(!Queue.isempty ()) { intk=Queue.remove (); for(inti=0;i<prerequisites.length;i++){ if(k==prerequisites[i][0]){ intL=prerequisites[i][1]; FLAG[L]--; if(flag[l]==0) {Count++; Queue.add (l); } } } } returncount==numcourses; }}
[Leedcode 207] Course Schedule