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.
Note:
这道题是拓扑排序,不过这道题里面其实就是求图里面有没有环。
思路是先用一个二维数组存下所有的对应课程组,然后算出每个点的入度。对于入度为0的课程进行BFS遍历,以0->1为例,如果从0找到1,就把1的入度减一。当1的入度也为0的时候,加入遍历的queue。这样,原则上每个点最后都会被遍历到,遍历的个数应该等于课程的数目。但是如果有环,有的点的入度不能变为0,遍历的个数就会少于课程总数。
public class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { if (numCourses == 0 || prerequisites == null) { return true; } int[][] matrix = new int[numCourses][numCourses]; int[] degree = new int[numCourses]; for (int i = 0; i < prerequisites.length; i++) { int pre = prerequisites[i][1]; int ready = prerequisites[i][0]; matrix[pre][ready] = 1; degree[ready]++; } Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < numCourses; i++) { if (degree[i] == 0) { q.offer(i); } } int count = 0; while (!q.isEmpty()) { int course = q.poll(); count++; for (int i = 0; i < numCourses; i++) { if (matrix[course][i] == 1) { degree[i]--; if (degree[i] == 0) { q.offer(i); } } } } return count == numCourses; } }
第一次做这种有向图题目,看了答案。。。到时候还是回顾一下吧。
原文:http://www.cnblogs.com/aprilyang/p/6385862.html