LeetCode 207 Course Schedule 拓扑排序BFS
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Solution
拓扑排序的模板题。每次建边从 \(b_i \rightarrow a_i\),然后 \(a_i\) 的度数 \(+1\)。每次取出度数为 \(0\) 的点加入队列,然后将删除这些点相连的边:即将 \(a_i\) 的度数 \(-1\),再将度数为 \(0\) 的点加入队列直到没有点满足条件。如果最后符合条件点数 \(=\ \text{numCourses}\),则为true;否则为false
点击查看代码
class Solution {
private:
vector vec[2004];
int deg[2002];
vector ans;
public:
bool canFinish(int numCourses, vector>& preq) {
for(int i=0;i