Problem
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?
ExampleGiven n = 2, prerequisites = [[1,0]]
Return true
Given n = 2, prerequisites = [[1,0],[0,1]]
Return false
</>复制代码
class Solution {
public boolean canFinish(int num, int[][] pre) {
//initialize graph: create list for each node(int)
if (pre.length > num*(num-1)/2) return false;
List[] graph = new ArrayList[num];
for (int i = 0; i < num; i++) graph[i] = new ArrayList<>();
//build graph: save children nodes to the corresponding list
//save indegrees of children nodes to indegree[] array
int[] indegree = new int[num];
for (int i = 0; i < pre.length; i++) {
indegree[pre[i][0]]++;
graph[pre[i][1]].add(pre[i][0]);
}
//create queue to do BFS
//save parent nodes which don"t have pre courses (indegree == 0) to the queue
Deque queue = new ArrayDeque<>();
for (int i = 0; i < num; i++) {
if (indegree[i] == 0) queue.offer(i);
}
//BFS: poll the parent nodes, if they have children, offer to the queue
int count = 0;
while (!queue.isEmpty()) {
Integer root = queue.poll();
count++;
List children = graph[root];
for (int child: children) {
if (indegree[child] == 1) {
queue.offer(child);
}
indegree[child]--;
}
}
return count == num;
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/69443.html
摘要:题目解答这是一个有向图问题,所以先建图,然后再扫。同时记录一共存了多少课程在里,这些课都是可以上的课。如果当两个点在同时访问的时候,那么构成死循环,返回。扫完所有的点都没问题,才返回。这里总是忘记,当中时,才否则继续循环 题目:There are a total of n courses you have to take, labeled from 0 to n - 1. Some c...
Problem 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...
Course Schedule I 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 e...
Problem 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 a...
摘要:建立入度组成,把原来输入的无规律,转换成另一种表示图的方法。找到为零的点,放到里,也就是我们图的入口。对于它的也就是指向的。如果这些的入度也变成,也就变成了新的入口,加入到里,重复返回结果。这里题目有可能没有预修课,可以直接上任意课程。 Some courses may have prerequisites, for example to take course 0 you have ...
阅读 4205·2021-11-25 09:43
阅读 2687·2021-11-18 13:11
阅读 2403·2019-08-30 15:55
阅读 3354·2019-08-26 11:58
阅读 2915·2019-08-26 10:47
阅读 2306·2019-08-26 10:20
阅读 1355·2019-08-23 17:59
阅读 3225·2019-08-23 15:54
极致性价比!云服务器续费无忧!
Tesla A100/A800、Tesla V100S等多种GPU云主机特惠2折起,不限台数,续费同价。
NVIDIA RTX 40系,高性价比推理显卡,满足AI应用场景需要。
乌兰察布+上海青浦,满足东推西训AI场景需要