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;

}

};

相关推荐
开心星人23 分钟前
Leetcode hot100 Java刷题(二)
java·算法·leetcode
liulilittle28 分钟前
CPU亲和性深度实践:从基础原理到Intel大小核架构优化
c++·线程·进程·cpu·量化·高频·亲核性
hn小菜鸡33 分钟前
LeetCode 153.寻找旋转排序数组中的最小值
数据结构·算法·leetcode
Albert Edison1 小时前
【项目设计】基于正倒排索引的Boost搜索引擎
linux·网络·c++·后端·http·搜索引擎
DeniuHe1 小时前
逻辑回归(Logistic Regression)详细解释与公式推导
算法·机器学习·逻辑回归
迅量科技资讯分享1 小时前
手机拍照明晰度评估:传感器尺寸像素数量与处理器算法解析
算法·三星·像素
liu****1 小时前
12.线程同步与互斥
linux·数据结构·c++·算法·1024程序员节
十五年专注C++开发1 小时前
DocxFactory: 一个C++操作word的开源库(不依赖office控件)
c++·开源·word·后端开发
麦烤楽鸡翅1 小时前
小红书推荐系统(牛客)
java·python·算法·秋招·春招·牛客·面试算法题
屁股割了还要学2 小时前
【C++进阶】STL-string的简单实现
c语言·开发语言·数据结构·c++·学习·考研