-
Notifications
You must be signed in to change notification settings - Fork 0
/
course_schedule.cpp
107 lines (94 loc) · 2.81 KB
/
course_schedule.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// https://leetcode.com/problems/course-schedule/
// May 12, 2016
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites)
{
populate_prerequisites_graph(numCourses, prerequisites);
// run a DFS loop
isDAG_ = true;
for (unsigned int course_i=0; (course_i != numCourses) && isDAG_; ++course_i)
{
dfs_traversal_recursive(course_i);
}
return isDAG_;
}
private:
void populate_prerequisites_graph(int numCourses, vector<pair<int, int>>& prerequisites)
{
adjacencyList_.reserve(numCourses);
for (unsigned int course_i=0; course_i != numCourses; ++course_i)
{
adjacencyList_.push_back(vector<int>());
}
for(vector<pair<int, int>>::iterator it = prerequisites.begin(); it != prerequisites.end(); ++it)
{
pair<int,int> prerequisitePair = *it;
int course1 = prerequisitePair.second;
int course2 = prerequisitePair.first;
adjacencyList_[course1].push_back(course2);
}
// initialize visited vector
vecVisited_.reserve(numCourses);
vecTempVisited_.reserve(numCourses);
for (unsigned int course_i=0; course_i != numCourses; ++course_i)
{
vecVisited_.push_back(false);
vecTempVisited_.push_back(false);
}
}
void dfs_traversal_recursive(int st_vertex)
{
if (vecTempVisited_[st_vertex])
{
isDAG_ = false; // There's a cycle in the directed graph.
return;
}
if (vecVisited_[st_vertex])
{
return;
}
vecTempVisited_[st_vertex] = true;
for (vector<int>::iterator it = adjacencyList_[st_vertex].begin(); it != adjacencyList_[st_vertex].end(); ++it)
{
int neighbor_vertex = *it;
dfs_traversal_recursive(neighbor_vertex);
}
vecTempVisited_[st_vertex] = false;
vecVisited_[st_vertex] = true;
}
private:
// Courses are labeled 0 to n-1
vector<vector<int> > adjacencyList_;
vector<bool> vecVisited_; // This stores permanent visit
vector<bool> vecTempVisited_;
bool isDAG_;
};
int main(int argc, char* argv[])
{
int numCourses;
vector<pair<int, int>> prerequisites;
numCourses = 2;
prerequisites.push_back(make_pair(1,0));
prerequisites.push_back(make_pair(0,1));
Solution sln;
bool can_finish = sln.canFinish(numCourses, prerequisites);
if (can_finish)
{
cout << "can finish" << endl;
}
else
{
cout << "can't finish" << endl;
}
return 0;
}
/**
https://en.wikipedia.org/wiki/Topological_sorting
TBD:
1. Iterative solution
2. Kahn's algorithm
*/