-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourse-schedule.cpp
More file actions
61 lines (47 loc) · 1.3 KB
/
Copy pathcourse-schedule.cpp
File metadata and controls
61 lines (47 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//
// Created by Chenguang Wang on 2024/2/13.
//
#include <vector>
using namespace std;
class Solution {
private:
vector<bool> visited;
vector<bool> onPath;
bool hasCycle = false;
vector<int> *buildGraph(int numCourses, vector<vector<int>> &prerequisites) {
auto *graph = new vector<int>[numCourses];
for (int i = 0; i < numCourses; i++) {
graph[i] = vector<int>();
}
for (auto &edge: prerequisites) {
int from = edge[1];
int to = edge[0];
graph[from].push_back(to);
}
return graph;
}
void traverse(vector<int> *graph, int s) {
if (onPath[s]) {
hasCycle = true;
}
if (visited[s] || hasCycle) {
return;
}
visited[s] = true;
onPath[s] = true;
for (auto t: graph[s]) {
traverse(graph, t);
}
onPath[s] = false;
}
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites) {
vector<int> *graph = buildGraph(numCourses, prerequisites);
visited = vector<bool>(numCourses, false);
onPath = vector<bool>(numCourses, false);
for (int i = 0; i < numCourses; i++) {
traverse(graph, i);
}
return !hasCycle;
}
};