207. Course Schedule (Medium)
https://leetcode.com/problems/course-schedule/
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.
Example 2:
Input: 2, [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have 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 about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
Solutions
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (numCourses == 0) {
return true;
}
int[] inDegree = new int[numCourses];
Arrays.fill(inDegree, 0);
int[][] relation = new int[numCourses][numCourses];
for (int i = 0; i < numCourses; i++) {
Arrays.fill(relation[i], 0);
}
for (int i = 0; i < prerequisites.length; i++) {
int[] pair = prerequisites[i];
// Course pair[1] is the prerequisite for course pair[0]
relation[pair[0]][pair[1]] = 1;
inDegree[pair[0]]++;
}
Queue<Integer> finished = new ArrayDeque<>();
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0) {
finished.offer(i);
}
}
int count = 0;
// Courses that can be finished will be added to finished lists. For those
// correlative dependent courses will never get into this list. So once finished
// list becomes empty, there are two situations: 1. all completed; 2. There are loops
// in the prerequisites graph.
while (!finished.isEmpty()) {
int course = finished.poll();
// scan all the courses that depends of current course
for (int i = 0; i < numCourses; i++) {
// See if course i depends on current course
if (relation[i][course] == 0) {
continue;
}
// already finished, continue
if (inDegree[i] == 0) {
continue;
}
// It stands for course i's completion once its in degree becomes 0.
if ((--inDegree[i]) == 0) {
finished.offer(i);
}
}
count++;
}
return count == numCourses;
}
}