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(onpaths){

hasCircle=true;

return ;

}

if(visiteds){

return;

}

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

onpaths=true;

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

visiteds=true;

for(int t:graphs){

traverse(graph,t);

}

onpaths=false;

}

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

//图中共有numCourses

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

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

graphi=vector<int>();

}

for(auto& edge:prerequisites){

int from=edge1,to=edge0;

graphfrom.push_back(to);

}

return graph;

}

};

相关推荐
To_OC12 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
炸膛坦客13 小时前
单片机/C/C++八股:(二十六)IIC 专题(I²C)---- 上集
c语言·c++·单片机
旖-旎13 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC13 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
Henry Zhu12313 小时前
C++中的特殊成员函数与智能指针
c++
delishcomcn14 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹14 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术15 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
_wyt00116 小时前
多重背包问题详解
c++·背包dp