-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourseScheduleII.cpp
More file actions
32 lines (30 loc) · 985 Bytes
/
courseScheduleII.cpp
File metadata and controls
32 lines (30 loc) · 985 Bytes
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
// Source: https://leetcode.com/problems/course-schedule-ii/
// Author: Miao Zhang
// Date: 2021-01-25
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
for (auto pre: prerequisites) {
graph[pre[0]].push_back(pre[1]);
}
vector<int> visited(numCourses, 0);
vector<int> path;
for (int i = 0; i < numCourses; i++) {
if (!dfs(graph, visited, i, path)) return {};
}
return path;
}
bool dfs(vector<vector<int>>& graph, vector<int>& visited,
int i, vector<int>& path) {
if (visited[i] == 1) return false;
if (visited[i] == 2) return true;
visited[i] = 1;
for (auto j: graph[i]) {
if (!dfs(graph, visited, j, path)) return false;
}
visited[i] = 2;
path.push_back(i);
return true;
}
};