Course Schedule
Problem:
See the about graph. There is a cycle. Visit 0 first, reduce 1's indegree by 1. Even so, there is no node that has indegree == 0. The DFS can only get 1 node.
Solution:
Use matrix to store graph is easier to implement.
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?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
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.
Analysis:
Use topological sort to check whether the graph has cycle.
Solution:
Use matrix to store graph is easier to implement.
class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { int[][] graph = new int[numCourses][numCourses]; // j -> i int[] indegree = new int[numCourses]; int count= 0; // in degree for (int i = 0; i < prerequisites.length; i++) { int pre = prerequisites[i][1]; int cur = prerequisites[i][0]; if (graph[cur][pre] == 0) { indegree[cur]++; } graph[cur][pre] = 1; } Queue<Integer> queue = new LinkedList<>(); for (int i = 0; i < numCourses; i++) { if (indegree[i] == 0) { queue.offer(i); } } while(!queue.isEmpty()) { int cur = queue.poll(); count++; // find cur's neighbours and reduce degree by 1 for (int i = 0; i < numCourses; i++) { if (graph[i][cur] == 1) { if (--indegree[i] == 0) { queue.offer(i); } } } } return count == numCourses; } }
评论
发表评论