Description
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.
Problem URL
Solution
给n个课程,以及课程之间的依赖关系的数组,判断在这些依赖之下能否take 所有的课程。本质上是一个有向图连通性的问题。
We use BFS to solve this problem. First, build a two-dimensional array graph to store edges. And an integer array to store indegree of each node(courses).
Then using a queue to store all nodes which do not have indegree. It means that they are prerequest courses. Poll them from the queue and count ++, then minus corresponding indegree. If indegree is 0, it means it could be offered in the queue.
Finally, if the count is equal to num of courses, that means true.
Code
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[][] graph = new int[numCourses][numCourses];
int[] indegree = new int[numCourses];
for (int i = 0; i < prerequisites.length; i++){
int pre = prerequisites[i][1];
int cur = prerequisites[i][0];
if (graph[pre][cur] == 0){
indegree[cur]++;//for duplicate case
}
graph[pre][cur] = 1;
}
int count = 0;
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++){
if (indegree[i] == 0){//no dependency, no indegree edge
queue.offer(i);
}
}
while (!queue.isEmpty()){
int pre = queue.poll();
count++;
for (int i = 0; i < numCourses; i++){
if (graph[pre][i] == 1){
indegree[i]--;
if (indegree[i] == 0){
queue.offer(i);
}
}
}
}
return count == numCourses;
}
}
Time Complexity: O(p + n)
Space Complexity: O(n^2)