Topic:
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.
Idea: first to test instructions some courses have first-class courses-these courses must first learn, similar to the following picture, this is the typical topological sort of a graph
Step 1: Find a vertex with a zero-in degree
Step 2: Delete this vertex
Step 3: Loop 1, 2 if all the vertices are gone, then there is a graph that can be completed.
The second is to understand the input of the algorithm in the problem numcourse the total number of classes to be selected and the prerequisite matrix is the prerequisite matrix (which has always been considered an adjacency matrix)
Therefore, the first step is to give the matrix, to convert the adjacency matrix (also can be adjacent linked list), and then step by step.
Code:
Public classSolution { Public BooleanCanfinish (intNumcourses,int[] Prerequisites) { int[] Indegree =New int[numcourses]; int[] Matrix =New int[Numcourses] [Numcourses];//[I][j] I is a prerequisite for J I->jstack<integer> stack =NewStack<integer>(); for(inti = 0; i < prerequisites.length; i++){ if(Matrix[prerequisites[i][1]][prerequisites[i][0]] = = 1)Continue;//input has duplicatesindegree[prerequisites[i][0]]++;//in degrees plus oneMatrix[prerequisites[i][1]][prerequisites[i][0]] = 1;//p [J]<-[i] } for(inti = 0; i < numcourses; i++){ if(Indegree[i] = = 0)//Push -in stack with zero penetrationStack.push (i); } while(!Stack.isempty ()) { inttemp = Stack.pop ();//Delete all lines that are connected to the zero-degree point for(inti = 0; i < numcourses; i++) {//each deletion of a corresponding in the degree minus one if(Matrix[temp][i] = = 1) {Matrix[temp][i]= 0; Indegree[i]--;//if the minus I corresponds to a degree of 0, it is put into the stack if(Indegree[i] = = 0) Stack.push (i); } } } for(inti = 0; i < numcourses; i++) {//determine if there are points that are not zero in degrees if(Indegree[i] > 0) return false; } return true; }}
[Leetcode-java] Course Schedule