LeetCode 210 course schedule 2
now instead of just checking on whether we can finish all the courses or not, we are now asked to return the order of courses that you should take to finish all the courses.
we only needs to return one path if there exist any of these paths
public int[] findOrder(int numCourses, int[][] prerequisites)
so the idea for this problem is:
we starting from each head we can found, and check them out on it’s every neighbor, and we go and go until the queue is empty(bfs) is finished. and during the whole process, keeps recording of every node we’ve been through, and in the last, check the number of different node we have been through, if the number is numCourses, then we found it, return the res.
BFS solution, using queue
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
int[] res = new int[numCourses];
int k = 0;
for (int[] pair : prerequisites) { //get the indegree of each node
indegree[pair[0]]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < indegree.length; i++) { //check which of indgree is 0, if it is 0, we can start from it
if (indegree[i] == 0) {
queue.offer(i);
res[k++] = i;
}
}
//now all of our head is in the queue
while (!queue.isEmpty()) {
int pre = queue.poll();
for (int[] pair : prerequisites) { //we check each pair
if (pair[1] == pre) {
indegree[pair[0]]--;
if (indegree[pair[0]] == 0) { //this should be 0, because otherwise it means there are other node that into this too
queue.offer(pair[0]);
res[k++] = pair[0];
}
}
}
}
return (k == numCourses) ? res : new int[0];
}
}
相關文章
- [LeetCode] 210. Course Schedule IILeetCode
- leetcode【210】【Depth-first Search】Course Schedule II【c++版本】LeetCodeC++
- LeetCode 207 Course ScheduleLeetCode
- 207. Course Schedule
- cocos2dx update scheduleUpdate to update or schedule(schedule_selector(fun),dt)
- kaggle course --NLP
- BUU XSS COURSE 1
- BUU BURP COURSE 1
- TVM:Schedule的理解
- SpringBoot 中的 @ScheduleSpring Boot
- [譯][A crash course in WebAssembly] assemblyWeb
- LeetCode2:LeetCode
- springboot整合schedule(深度理解)Spring Boot
- schedule 定時任務
- TypeScript Crash Course: Property Access ModifiersTypeScript
- pwn.college Fundementals Assembly Crash Course
- LeetCode 2——兩數相加LeetCode
- leetcode 231 2的冪LeetCode
- LeetCode 2 Add Two NumbersLeetCode
- 【LeetCode】2 兩數相加LeetCode
- 【leetcode】【2、兩數相加】LeetCode
- python 定時任務之 schedulePython
- Uncode-Schedule框架原始碼分析框架原始碼
- ZOJ 3956——Course Selection System(01揹包)
- WSL2連線USB裝置(以USRP B210為例)
- 第 210 場周賽
- LeetCode-2 Add Two NumbersLeetCode
- [LeetCode] 518. Coin Change 2LeetCode
- LeetCode 2. Add Two NumbersLeetCode
- leetcode 2. 兩數相加LeetCode
- LeetCode 2.兩數相加LeetCode
- QT210開發板學習(2): 透過DNW點亮LED燈QT
- 使用 telescope 檢視 schedule 執行狀態
- Leetcode Meeting room問題系列 - 2LeetCodeOOM
- LeetCode - 15. 三數之和 2LeetCode
- LeetCode題集-2 - 兩數相加LeetCode
- [Java] 藍橋杯ADV-210 演算法提高 2-1螢幕列印Java演算法
- Schedule 排程系統設計(單機版)