LeetCode:207. 课程表

class Solution {

public:

// 记录递归堆栈的结点

vector<bool> onpath;

vector<bool> visited;

// 记录是否成环

bool hasCircle = false;

bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {

auto graph=buildGraph(numCourses,prerequisites);

//设置大小为numCourse的数组

onpath=vector<bool>(numCourses);

visited=vector<bool>(numCourses);

for(int i=0;i<numCourses;i++){

//遍历图中所有节点

traverse(graph,i);

}

//只要没有循环依赖就可以完成所有课程

return !hasCircle;

}

void traverse(vector<vector<int>>& graph,int s){

if(hasCircle){

//说明已经成环

return ;

}

if(onpath[s]){

hasCircle=true;

return ;

}

if(visited[s]){

return;

}

//记录已经访问过结点s

onpath[s]=true;

//将已经访问过过的结点s标记

visited[s]=true;

for(int t:graph[s]){

traverse(graph,t);

}

onpath[s]=false;

}

vector<vector<int>>buildGraph(int numCourses, vector<vector<int>>& prerequisites){

//图中共有numCourses

vector<vector<int>>graph(numCourses);

for(int i=0;i<numCourses;i++){

graph[i]=vector<int>();

}

for(auto& edge:prerequisites){

int from=edge[1],to=edge[0];

graph[from].push_back(to);

}

return graph;

}

};

相关推荐
代大大2 小时前
sciter.js 之cpp使用教程(1)
c++·前端框架
liu****3 小时前
19.map和set的封装
开发语言·数据结构·c++·算法
孤廖3 小时前
C++ 模板再升级:非类型参数、特化技巧(含全特化与偏特化)、分离编译破解
linux·服务器·开发语言·c++·人工智能·后端·深度学习
水冗水孚3 小时前
双指针算法在实际开发中的具体应用之代码Review文章字符串的片段分割
算法·leetcode
DuHz3 小时前
用于汽车雷达应用的步进频率PMCW波形——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理·毫米波雷达
张晓~183399481213 小时前
碰一碰发抖音源码技术搭建部署方案
线性代数·算法·microsoft·矩阵·html5
weixin_448119943 小时前
Datawhale人工智能的数学基础 202510第3次作业
人工智能·算法
田野追逐星光3 小时前
STL中容器string -- 讲解超详细
c++
CoovallyAIHub3 小时前
全球OCR新标杆!百度0.9B小模型斩获四项SOTA,读懂复杂文档像人一样自然
深度学习·算法·计算机视觉