-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path207.cpp
96 lines (75 loc) · 2.44 KB
/
207.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
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
//search for no cycle
if(prerequisites.size() == 0) return true;
int n = numCourses;
//make adjacency list first
vector< vector<int> > edges(n);
for (auto &i : prerequisites){
edges[i[1]].push_back(i[0]);
}
vector<int>visited(n, 0); //0 is not visited, 1 is visited
vector<int>in_stack(n , 0);
//do dfs to check for the finish time
stack<int>for_dfs;
for (int i = 0 ; i <n ; i++){
if(visited[i] == 0){
for_dfs.push(i);
in_stack[i] = 1;
}
while(!for_dfs.empty()){
int cur = for_dfs.top();
visited[cur] = 1;
in_stack[cur]= 1;
//all neighbors have been transversed
if(edges[cur].size() == 0 ){
for_dfs.pop();
in_stack[cur] = 0;
}
else{
if (visited[edges[cur].back()] == 0){ //not yet visited, push to stack
for_dfs.push(edges[cur].back());
}
if (in_stack[edges[cur].back()] == 1) return false;
edges[cur].erase(edges[cur].end()-1);
}
}
}
return true;
}
};
//other solution
/*
kahn algo
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector <vector<int>> graph(numCourses, vector<int>());
vector <int> indegree(numCourses, 0);
for (auto &i : prerequisites){
graph[i[0]].push_back(i[1]);
indegree[i[1]]++;
}
stack<int>zero_deg;
for(int i = 0 ; i < numCourses; i++){
if(indegree[i] == 0){
zero_deg.push(i);
}
}
while(!zero_deg.empty()){
int cur = zero_deg.top();
zero_deg.pop();
numCourses--;
//transversing through the neighbors
for (auto &i : graph[cur]){
indegree[i]--;
if(indegree[i] == 0)
zero_deg.push(i);
}
}
//if no vertex remain in the graph, then it is possible to make a schedule
return numCourses == 0 ? true : false;
}
};
*/