您的位置:首页 > 其它

207. Course Schedule

2016-03-22 10:20 253 查看
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:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how
a graph is represented.

click to show more hints.

Subscribe to see which companies asked this question
总之从前度为0的开始移除就对了

public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {

// init the adjacency list
List<Set> posts = new ArrayList<Set>();
for (int i = 0; i < numCourses; i++) {
posts.add(new HashSet<Integer>());
}

// fill the adjacency list
for (int i = 0; i < prerequisites.length; i++) {
posts.get(prerequisites[i][0]).add(prerequisites[i][1]);
}

// count the pre-courses
int[] preNums = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
Set set = posts.get(i);
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
preNums[it.next()]++;
}
}

// remove a non-pre course each time
for (int i = 0; i < numCourses; i++) {
// find a non-pre course
int j = 0;
for ( ; j < numCourses; j++) {

869b
if (preNums[j] == 0) break;
}

// if not find a non-pre course
if (j == numCourses) return false;

preNums[j] = -1;

// decrease courses that post the course
Set set = posts.get(j);
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
preNums[it.next()]--;
}
}

return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: