标签:nis ssi course div lse als label schedule ISE
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?
Example 1:
Input: 2, [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { if (numCourses == 0 || prerequisites == null) { return false; } int[] indegree = new int[numCourses]; for (int[] pres : prerequisites) { indegree[pres[0]] += 1; } int res = numCourses; Queue<Integer> queue = new LinkedList<>(); for (int i = 0; i < indegree.length; i++) { if (indegree[i] == 0) { queue.offer(i); } } while(!queue.isEmpty()) { Integer cur = queue.poll(); res -= 1; for (int[] pres: prerequisites) { if (pres[1] == cur) { // for a -> b, minus degree of a indegree[pres[0]] -= 1; if (indegree[pres[0]] == 0) { queue.offer(pres[0]); } } } } return res == 0; } }
标签:nis ssi course div lse als label schedule ISE
原文地址:https://www.cnblogs.com/xuanlu/p/12255214.html