210. Course Schedule II

  • 26.5%

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

1
2
3
For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

1
4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

Hints:

  1. This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.

https://discuss.leetcode.com/topic/17276/20-lines-c-bfs-dfs-solutions

20+ lines C++ BFS/DFS Solutions

Well, this problem is spiritually similar to to Course Schedule. You only need to store the nodes in the order you visit into a vector during BFS or DFS. Well, for DFS, a final reversal is required.

BFS

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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
vector<int> degrees = compute_indegree(graph);
queue<int> zeros;
for (int i = 0; i < numCourses; i++)
if (!degrees[i]) zeros.push(i);
vector<int> toposort;
for (int i = 0; i < numCourses; i++) {
if (zeros.empty()) return {};
int zero = zeros.front();
zeros.pop();
toposort.push_back(zero);
for (int neigh : graph[zero]) {
if (!--degrees[neigh])
zeros.push(neigh);
}
}
return toposort;
}
private:
vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
vector<int> compute_indegree(vector<unordered_set<int>>& graph) {
vector<int> degrees(graph.size(), 0);
for (auto neighbors : graph)
for (int neigh : neighbors)
degrees[neigh]++;
return degrees;
}
};

DFS

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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
vector<int> toposort;
vector<bool> onpath(numCourses, false), visited(numCourses, false);
for (int i = 0; i < numCourses; i++)
if (!visited[i] && dfs(graph, i, onpath, visited, toposort))
return {};
reverse(toposort.begin(), toposort.end());
return toposort;
}
private:
vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
bool dfs(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited, vector<int>& toposort) {
if (visited[node]) return false;
onpath[node] = visited[node] = true;
for (int neigh : graph[node])
if (onpath[neigh] || dfs(graph, neigh, onpath, visited, toposort))
return true;
toposort.push_back(node);
return onpath[node] = false;
}
};

https://discuss.leetcode.com/topic/23925/python-dfs-bfs-solutions-with-comments

Python dfs, bfs solutions with comments.

BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def findOrder1(self, numCourses, prerequisites):
dic = {i: set() for i in xrange(numCourses)}
neigh = collections.defaultdict(set)
for i, j in prerequisites:
dic[i].add(j)
neigh[j].add(i)
# queue stores the courses which have no prerequisites
queue = collections.deque([i for i in dic if not dic[i]])
count, res = 0, []
while queue:
node = queue.popleft()
res.append(node)
count += 1
for i in neigh[node]:
dic[i].remove(node)
if not dic[i]:
queue.append(i)
return res if count == numCourses else []

DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def findOrder(self, numCourses, prerequisites):
dic = collections.defaultdict(set)
neigh = collections.defaultdict(set)
for i, j in prerequisites:
dic[i].add(j)
neigh[j].add(i)
stack = [i for i in xrange(numCourses) if not dic[i]]
res = []
while stack:
node = stack.pop()
res.append(node)
for i in neigh[node]:
dic[i].remove(node)
if not dic[i]:
stack.append(i)
dic.pop(node)
return res if not dic else []

https://discuss.leetcode.com/topic/13982/c-using-3-colored-approach

[C++] Using 3 colored approach

Here, i have used 3 colored approach. Here w -> represent white means vertex yet not visited.
g -> gray , it means it is under DFS recursion and we again found the same node. This means cycle exists and return false.

b -> black node when DFS is done visiting the node.

This method checks cycle as well as keeps storing answer in stack in case cycle doesn’t exists.

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
class Graph {
public:
int v;
list <int> *adj;
Graph(int v)
{
this->v=v;
adj = new list<int> [v];
}
void addedges(int src , int dest)
{
adj[dest].push_back(src);
}
};
class Solution {
public:
stack <int> st;
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
Graph g(numCourses);
for (int i=0 ; i < prerequisites.size() ; i++)
g.addedges(prerequisites[i].first , prerequisites[i].second);
vector <int> ans;
if(!courseScheduleCheck(g))
return ans;
while(!st.empty())
{
ans.push_back(st.top());
st.pop();
}
return ans;
}
bool courseScheduleCheck(Graph g)
{
int v = g.v;
vector <char> visit(v,'w');
for(int i=0 ; i<v;i++)
{
if(visit[i]== 'w')
if(iscycle(g,i,visit))
return false;
}
return true;
}
bool iscycle(Graph g , int i, vector <char> & visit)
{
list <int> ::iterator it;
for(it = g.adj[i].begin() ; it!=g.adj[i].end() ; it++)
{
if(visit[*it]== 'g')
return true;
else
{
if(visit[*it] != 'b')
{
visit[*it] = 'g';
if(iscycle(g,*it,visit))
return true;
}
}
}
visit[i]='b';
st.push(i);
return false;
}
};
谢谢你,可爱的朋友。