207. 课程表
- 207. 课程表
- 思路:bfs和dfs都行,看注释
- 时间和空间:O(n + m)
class Solution {
private:
vector<vector<int>>graph;
vector<int>in;
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
graph.resize(numCourses);
in.resize(numCourses);
for(auto& i : prerequisites){
graph[i[1]].push_back(i[0]);
++in[i[0]];
}
queue<int>q;
for(int i = 0; i < numCourses; i++){
if(in[i] == 0){
q.push(i);
}
}
int count = 0;
while(!q.empty()){
++count;
int temp = q.front();
q.pop();
for(int it : graph[temp]){
--in[it];
if(in[it] == 0){
q.push(it);
}
}
}
return count == numCourses;
}
};
210. 课程表 II
class Solution {
private:
vector<vector<int>>graph;
vector<int>in;
vector<int>ret;
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
graph.resize(numCourses);
in.resize(numCourses);
for(auto it : prerequisites){
graph[it[1]].push_back(it[0]);
++in[it[0]];
}
queue<int>q;
for(int i = 0; i < numCourses; i++){
if(in[i] == 0){
q.push(i);
}
}
while(!q.empty()){
int temp = q.front();
q.pop();
ret.push_back(temp);
for(auto it : graph[temp]){
--in[it];
if(in[it] == 0){
q.push(it);
}
}
}
if(ret.size() != numCourses) return vector<int>{};
return ret;
}
};