class Solution {
public:
//是课程表207题的升级版,不同是结果需要输出顺序数组
//不同的地方作了标注,思路不懂的建议先翻看第207题的注释
vector<vector<int>> vecVecInt;
vector<int> visited;
bool flag = true;
vector<int> ans;
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
visited.resize(numCourses);
vecVecInt.resize(numCourses);
for(auto i : prerequisites)
vecVecInt[i[0]].push_back(i[1]);
for(int i = 0; i < numCourses && flag; ++i){
if(!visited[i]) //这里必须加上,不然会重复输出,且能提升效率
dfs(i);
}
if(flag) //如果能学完全部课程,输出答案
return ans;
else //否则返回空数组
return {};
}
void dfs(int n){
visited[n] = 1;
int size = vecVecInt[n].size();
for(int i = 0; i < size; ++i){
if(flag && visited[vecVecInt[n][i]] == 0){
dfs(vecVecInt[n][i]);
if(!flag)
return;
}
else if(visited[vecVecInt[n][i]] == 1){
flag = false;
return;
}
}
visited[n] = 2;
ans.push_back(n); //深度遍历,所以放在最后即可
}
};
Accepted
44/44 cases passed (24 ms)
Your runtime beats 31.18 % of cpp submissions
Your memory usage beats 20.07 % of cpp submissions (14.2 MB)