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.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more on how a graph is represented.
Click to show more hints.
Solution: Topological sort topological sort
The code is as follows:
public class Solution {public boolean canfinish (int numcourses, int[][] prerequisites) {int [][]matrix=new int] [Numcourses] [Numcourses]; int [] Indegree =new int[numcourses]; int len=prerequisites.length; for (int i=0;i<len;i++) {int ready=prerequisites[i][0]; int pre=prerequisites[i][1]; if (matrix[pre][ready] = = 0)//prevent repeated conditions indegree[ready]++; Matrix[pre][ready]=1; } 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; }}
Operation Result:
(Medium) Leetcode 207.Course Schedule