207. Course Schedule
public static boolean canFinish(int numCourses, int[][] prerequisites) {
// 参数检查
if (prerequisites == null) {
return false;
}
int len = prerequisites.length;
if (numCourses <= 0 || len == 0) {
return true;
}
// 记录每个course的prerequisites的数量
int[] pCounter = new int[numCourses];
for (int i = 0; i < len; i++) {
pCounter[prerequisites[i][0]]++;
}
// 用队列记录可以直接访问的course
LinkedList<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (pCounter[i] == 0) {
queue.add(i);
}
}
// 取出队列的course,判断
int numNoPre = queue.size();
while (!queue.isEmpty()) {
int top = queue.remove();
for (int i = 0; i < len; i++) {
// 该course是某个course的prerequisites
if (prerequisites[i][1] == top) {
pCounter[prerequisites[i][0]]--;
if (pCounter[prerequisites[i][0]] == 0) {
numNoPre++;
queue.add(prerequisites[i][0]);
}
}
}
}
return numNoPre == numCourses;
}
本文标题:207. Course Schedule
本文链接:https://www.haomeiwen.com/subject/wdanbxtx.html
网友评论