-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path207-course-schedule.cpp
72 lines (69 loc) · 1.61 KB
/
207-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
class Solution {
public:
vector<vector<bool>> g;
vector<bool> passNodes;
vector<int> res;
int l;
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
if (numCourses == 0)
{
return true;
}
l = numCourses;
int len = prerequisites.size();
for (int i = 0; i < numCourses; i++)
{
passNodes.push_back(false);
res.push_back(-1);
}
for (int i = 0; i < numCourses; i++)
{
g.push_back(passNodes);
}
for (int i = 0; i < len; i++)
{
g[prerequisites[i].first][prerequisites[i].second] = true;
}
for (int i = 0; i < numCourses; i++)
{
if (res[i] == -1)
{
bool flag = dfs(i);
if (!flag)
{
return false;
}
else
{
res[i] = 1;
}
}
}
return true;
}
bool dfs(int node)
{
passNodes[node] = true;
for (int i = 0; i < l; i++)
{
if (g[node][i])
{
if (passNodes[i])
{
return false;
}
bool flag = dfs(i);
if (!flag)
{
return false;
}
else
{
res[i] = 1;
}
}
}
passNodes[node] = false;
return true;
}
};