-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcourseSchedule1CanFinish.cpp
69 lines (54 loc) · 1.85 KB
/
courseSchedule1CanFinish.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
#include <iostream>
#include <vector>
#include <numeric>
#include <map>
#include <algorithm>
#include <set>
using std::vector;
using std::map;
using std::for_each;
using std::set;
using std::all_of;
bool dfs(int crs, set<int> visitSet, map<int,vector<int>> preMap){
if (visitSet.find(crs) != visitSet.end())
return false;
if (preMap[crs].empty())
return true;
visitSet.insert(crs);
bool allFinishable = all_of(preMap[crs].begin(), preMap[crs].end(), [&visitSet, &preMap](int pre){
return dfs(pre, visitSet, preMap);
});
if(!allFinishable)
return false;
visitSet.erase(crs);
preMap[crs].clear();
return true;
}
bool canFinish (int numCourses, vector<vector<int>>& prerequisites){
// Map each course to prerequisites list
vector<int> courses(numCourses);
std::iota(courses.begin(), courses.end(), 0);
map<int,vector<int>> preMap{};
// Initialize map of course to prerequisites. Each course will start with an empty vector
// of prerequisites
for_each(courses.begin(), courses.end(), [&preMap](int crs){preMap[crs] = vector<int>{};});
// Map each course to prerequisites
for_each(prerequisites.begin(), prerequisites.end(), [&preMap](vector<int>& preReqVec){
int crs {preReqVec[0]};
int pre {preReqVec[1]};
preMap[crs].push_back(pre);
});
// Set for course nodes we are currently visiting in the graph
set<int> visitSet{};
//Visit all courses along the current depth first search dfs
bool isFinishable = all_of(courses.begin(), courses.end(), [&preMap, &visitSet](int crs){
return dfs(crs,visitSet, preMap);
});
return isFinishable;
}
int main (){
vector<vector<int>> input{{0,1}, {0,2}, {1,3}, {1,4}, {3,4}};
bool isFinishable{canFinish(input.size(), input)};
std::cout << "Can we finish: " << isFinishable << std::endl;
return 0;
}