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;

}

};

相关推荐
天天爱吃肉82181 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
alphaTao1 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习1 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
阿猿收手吧!1 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++
颜酱1 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
不知名XL2 小时前
day50 单调栈
数据结构·算法·leetcode
Word码2 小时前
[C++语法] 继承 (用法详解)
java·jvm·c++
@––––––2 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
lxl13072 小时前
C++算法(1)双指针
开发语言·c++
xsyaaaan2 小时前
代码随想录Day31动态规划:1049最后一块石头的重量II_494目标和_474一和零
算法·动态规划