题目描述
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?
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 it is possible.
一共 n 门课,在一个[]里,要先完成右边的才能完成左边的,判断给出的课程是否能完成。
解题思路
拓扑排序,用邻接链表来表示课程,每个节点就是一门课,所以有 n 节点。根据[]来构造这个表graph。例如[0,1],则存在一条边从节点1指向节点0,再用一个数组indegree表示每个节点的入度(这个可以在构造邻接表的时候顺便完成)。
现在,有了入度数组,有了邻接表,就可以开始给它们进行拓扑排序了。每次挑出一个入度为0的节点,将它指向其他节点的边统统删除(对应节点入度--),这里有一点要注意——因为到最后,所有点都可能是入度为0,为了区分处理前后的点,增加一个visited数组,处理之后置为真,然后遍历所有节点,找到入度为0且visited为假的点,进行删边处理。同时还要有一个计数入度为0的节点的计数器cnt,最后,计数器 == n则能完成课程,否则不能。
代码如下
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int> > graph(numCourses);
vector<int> indegree(numCourses, 0);
vector<bool> visited(numCourses, false);
for (int i = 0; i < prerequisites.size(); i++) {
pair<int, int> pair1 = prerequisites[i];
graph[pair1.second].push_back(pair1.first);
indegree[pair1.first]++;
}
int cnt = 0;
for (int i = 0; i < graph.size(); i++) {
if (indegree[i] == 0 && !visited[i]) {
cnt++;
visited[i] = true;
for (int j = 0; j < graph[i].size(); j++) {
indegree[graph[i][j]]--;
}
i = -1;
}
}
return cnt == numCourses;
}
};
因为题目就是简单的拓扑排序,因此这里就简略写出解题过程。