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 Dequequeue = 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 ...
阅读 3683·2021-11-25 09:43
阅读 2599·2021-11-18 13:11
阅读 2193·2019-08-30 15:55
阅读 3271·2019-08-26 11:58
阅读 2823·2019-08-26 10:47
阅读 2229·2019-08-26 10:20
阅读 1270·2019-08-23 17:59
阅读 2997·2019-08-23 15:54