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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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 ...
閱讀 3710·2021-11-25 09:43
閱讀 2605·2021-11-18 13:11
閱讀 2213·2019-08-30 15:55
閱讀 3277·2019-08-26 11:58
閱讀 2829·2019-08-26 10:47
閱讀 2234·2019-08-26 10:20
閱讀 1278·2019-08-23 17:59
閱讀 3010·2019-08-23 15:54