Skip to content

Commit 30b6f54

Browse files
committed
Add Q207
1 parent e8a8bde commit 30b6f54

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

207_CourseSchedule/CourseShedule.cc

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public:
3+
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
4+
vector<vector<int>> inGraph(numCourses, vector<int>());
5+
vector<vector<int>> outGraph(numCourses, vector<int>());
6+
vector<bool> okCourse(numCourses, true);
7+
8+
for (auto&& prerequisite : prerequisites) {
9+
outGraph[prerequisite.first].push_back(prerequisite.second);
10+
inGraph[prerequisite.second].push_back(prerequisite.first);
11+
okCourse[prerequisite.first] = false;
12+
okCourse[prerequisite.second] = false;
13+
}
14+
while (true) {
15+
bool changed = false;
16+
for (int i = 0; i < numCourses; ++i) {
17+
if (okCourse[i]) continue;
18+
19+
if (inGraph[i].empty()) {
20+
okCourse[i] = true;
21+
for (int j = 0; j < outGraph[i].size(); ++j) {
22+
changed = true;
23+
auto it = find(std::begin(inGraph[outGraph[i][j]]), std::end(inGraph[outGraph[i][j]]), i);
24+
if (it != std::end(inGraph[outGraph[i][j]])) {
25+
inGraph[outGraph[i][j]].erase(it);
26+
}
27+
}
28+
}
29+
}
30+
if (!changed) {
31+
break;
32+
}
33+
}
34+
for (int i = 0; i < numCourses; ++i) {
35+
if (!okCourse[i]) return false;
36+
}
37+
return true;
38+
}
39+
};

0 commit comments

Comments
 (0)