什么是拓扑排序?简而言之就是把有向图从复杂的立体的图的表示形式转化为线性的表示形式,对于图中所有的边(u, v),在拓扑排序后的结果中节点u的位置一定在节点v之前。拓扑排序可以用来解决先修课程、工程施工等常见的实际问题,将这种“要有A必须现有B”的关系抽象为图中A指向B的有向边,将整个问题的解决转化为寻找一条从开始点到结束点的路径。直接看题。
207. Course Schedule
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, is it possible for you to finish all courses?
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 it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
- This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
- Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
- Topological sort could also be done via BFS.
题目的Hint很直接的提示了问题的本质,并提供拓扑排序和DFS的思路。拓扑排序基于Kahn算法,Kahn算法在Wikipedia中被用如下的Pseudocode解释:
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edge
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
总而言之就是不停的寻找入度为0的节点,将它加入拓扑排序的结果L中,删除从它出发的所有边,...... 循环该过程直到所有节点都被加入到L中。要判断是否有环,需要加入一个计数器,判断这个过程中有多少个节点的入度为0、已经被删除,如果这个总数和总节点数相同就说明所有节点都被放到了拓扑排序的结果中去,该有向图可以被映射到线性拓扑结构上去,因此不含环。
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> indegree(numCourses,0);
for(auto edge : prerequisites)
{
graph[edge.second].push_back(edge.first); // graph[i] contains all courses that take i as prerequisite
fo++indegree[edge.first];
}
queue<int> Q;
for(int i = 0;i < numCourses;i++)
if(indegree[i] == 0)
Q.push(i);
int counter = 0;
while(!Q.empty())
{
int u = Q.front();
Q.pop();
++counter;
for(auto v : graph[u])
{
if(--indegree[v] == 0)
Q.push(v);
}
}
return counter == numCourses;
}
210. Course Schedule II
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.
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]
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:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
vector<int> indegree(numCourses, 0);
vector<int> res;
for (auto edge : prerequisites) {
graph[edge.second].push_back(edge.first);
indegree[edge.first] += 1;
}
queue<int> Q;
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
Q.push(i);
}
}
int count = 0;
while (!Q.empty()) {
int u = Q.front();
Q.pop();
res.push_back(u);
count += 1;
for (auto v : graph[u]) {
if (--indegree[v] == 0) {
Q.push(v);
}
}
}
return count == numCourses ? res : vector<int>();
}