-
Notifications
You must be signed in to change notification settings - Fork 0
/
CourseSchedule.cpp
50 lines (39 loc) · 1.24 KB
/
CourseSchedule.cpp
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
class Solution {
public:
bool DFS(int v, vector<bool>* visited, vector<bool>* curr_visited,
vector<int>* graph) {
(*visited)[v] = true;
(*curr_visited)[v] = true;
for (int i = 0; i < graph[v].size(); i++) {
int u = graph[v][i];
if ((*curr_visited)[u]) {
return false;
}
if (!(*visited)[u]) {
if (!DFS(u, visited, curr_visited, graph)) {
return false;
}
}
}
(*curr_visited)[v] = false;
return true;
}
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<int>* graph = new vector<int>[numCourses];
for (int i = 0; i < prerequisites.size(); i++) {
int a_i = prerequisites[i][0];
int b_i = prerequisites[i][1];
graph[a_i].push_back(b_i);
}
vector<bool> visited(numCourses);
vector<bool> curr_visited(numCourses);
for (int i = 0; i < numCourses; i++) {
if (!visited[i]) {
if (!DFS(i, &visited, &curr_visited, graph)) {
return false;
}
}
}
return true;
}
};