There are a total of n courses you have to take, labeled from 0
to n - 1
.express
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, return the ordering of courses you should take to finish all courses.ui
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.spa
For example:code
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
blog
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]
. Another correct ordering is[0,2,1,3]
.ip
本題與207題思路同樣,只是返回值由bool型換爲整型數組,思路也沒變,耗時568ms。it
步驟:class
(1)初始化一個大小爲numCourses的數組grap;sed
(2)將圖中個節點的入度保存到數組中,將數組中第一個入度爲0的節點找出,並將該節點在數組中的值設爲-1,將數組中全部以該頂點爲入度的頂點入度減一,將其push到vector中;
(3)重複(2)numCourses次,若期間在grap數組中沒有找到入度爲0的頂點,則返回空;
1 vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) 2 { 3 int grap[numCourses]={0}; 4 vector<int> order; 5 for (int i=0;i<prerequisites.size();i++) 6 grap[prerequisites[i].first]++; 7 for (int j=numCourses-1;j>=0;--j) 8 { 9 int del=-1; 10 for (int k=0;k<numCourses;k++) 11 { 12 if (grap[k]==0) 13 { 14 del=k; 15 grap[k]=-1; 16 order.push_back(k); 17 break; 18 } 19 } 20 if(del==-1) 21 { 22 order.clear(); 23 return order; 24 } 25 for (int i=0;i<prerequisites.size();i++) 26 { 27 if (prerequisites[i].second==del) 28 grap[prerequisites[i].first]--; 29 } 30 } 31 return order; 32 }