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, is it possible for you to finish all courses?ui
For example:spa
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.code
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.blog
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.排序
题的本意就是拓扑排序,个人方法比较笨,也容易理解,就是按照拓扑排序的方法解题,464ms。ci
步骤:get
(1)初始化一个大小为numCourses的数组grap;input
(2)将图中个节点的入度保存到数组中,将数组中第一个入度为0的节点找出,并删除与它相关的边,并将该节点在数组中的值设为-1,其余节点赋值为0;
(3)重复(2)numCourses次,若图中边为0,这返回true,不然返回false;
1 bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) 2 { 3 int grap[numCourses]={0}; 4 for (int j=numCourses-1;j>=0;--j) 5 { 6 int del=-1; 7 for (int i=0;i<prerequisites.size();i++) 8 grap[prerequisites[i].first]++; 9 for (int k=0;k<numCourses;k++) 10 { 11 if (grap[k]==0) 12 { 13 del=k; 14 break; 15 } 16 } 17 if(del==-1) 18 break; 19 vector<pair<int, int>>::iterator its; 20 for (its=prerequisites.begin();its!=prerequisites.end();) 21 { 22 if (its->second==del) 23 its=prerequisites.erase(its); 24 else 25 ++its; 26 } 27 grap[del]=-1; 28 for (int p=0;p<numCourses;p++) 29 { 30 if (grap[p]!=-1) 31 grap[p]=0; 32 } 33 } 34 if(prerequisites.size()>0) 35 return false; 36 return true; 37 }
改进:(340ms)
维护一个数组,数组中存放图中各顶点入度,若顶点入度为0,将数组中全部以该顶点为入度的顶点入度减一。循环numCourses次,如循环中出现数组中全部顶点度都不为0,return false.
1 bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) 2 { 3 int grap[numCourses]={0}; 4 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 break; 17 } 18 } 19 if(del==-1) 20 return false; 21 for (int i=0;i<prerequisites.size();i++) 22 { 23 if (prerequisites[i].second==del) 24 grap[prerequisites[i].first]--; 25 } 26 } 27 return true; 28 }