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;

}

};

相关推荐
在黎明的反思1 天前
进程通信之消息队列(IPC)
算法
老鱼说AI1 天前
算法基础教学第一步:数据结构
数据结构·python·算法
极地星光1 天前
C++链式调用设计:打造优雅流式API
服务器·网络·c++
Jing_Rainbow1 天前
【LeetCode Hot100 刷题日记(19/100)】54. 螺旋矩阵 —— 数组、矩阵、模拟、双指针、层序遍历🌀
算法·面试·程序员
小陈要努力1 天前
Visual Studio 开发环境配置指南
c++·opengl
程序猿本员1 天前
5. 实现
c++
Bona Sun1 天前
单片机手搓掌上游戏机(十五)—pico运行fc模拟器之编译环境
c语言·c++·单片机·游戏机
地平线开发者1 天前
征程 6 | linear 高精度输出配置方式
算法·自动驾驶
小尧嵌入式1 天前
C++基础语法总结
开发语言·c++·stm32·单片机·嵌入式硬件·算法
white-persist1 天前
【攻防世界】reverse | IgniteMe 详细题解 WP
c语言·汇编·数据结构·c++·python·算法·网络安全