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;

}

};

相关推荐
郝学胜-神的一滴8 小时前
Linux的pthread_self函数详解:多线程编程中的身份标识器
linux·运维·服务器·开发语言·c++·程序人生
HUST8 小时前
C 语言 第七讲:数组和函数实践:扫雷游戏
c语言·开发语言·数据结构·vscode·算法·游戏·c#
oioihoii8 小时前
C++高并发编程核心技能解析
开发语言·c++
玖剹9 小时前
字符串相关题目
c语言·c++·算法·leetcode
llz_1129 小时前
图(邻接表)-(DFS/BFS)-Dijkstra
算法·深度优先·dijkstra·宽度优先
jimy19 小时前
程序崩溃free(): double free detected in tcache 2
linux·开发语言·数据结构·链表
派葛穆9 小时前
机器人-六轴机械臂的逆运动学
算法·机器学习·机器人
千里马-horse9 小时前
AsyncContext
开发语言·前端·javascript·c++·napi·asynccontext
宠..9 小时前
为单选按钮绑定事件
运维·服务器·开发语言·数据库·c++·qt·microsoft
那雨倾城9 小时前
用 YOLO Pose + Segmentation 在PiscCode构建“语义佛光”:一次实时视觉语义融合实验
图像处理·python·opencv·算法·yolo·计算机视觉·视觉检测