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, return the ordering of courses you should take to finish all courses.
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.
For example:
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]
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]
.
本题与207题思路一样,只是返回值由bool型换为整型数组,思路也没变,耗时568ms。
步骤:
(1)初始化一个大小为numCourses的数组grap;
(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 }