LC 207 210 Course Schedule I / II BFS 有向图的拓扑排序,并应用于探测是否存在环

什么是拓扑排序?简而言之就是把有向图从复杂的立体的图的表示形式转化为线性的表示形式,对于图中所有的边(u, v),在拓扑排序后的结果中节点u的位置一定在节点v之前。拓扑排序可以用来解决先修课程、工程施工等常见的实际问题,将这种“要有A必须现有B”的关系抽象为图中A指向B的有向边,将整个问题的解决转化为寻找一条从开始点到结束点的路径。直接看题。

207Course 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:

  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.

click to show more hints.

Hints:
  1. 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.
  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.

题目的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;
}

210Course 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:

  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.
和之前的题目一样,只不过要求输出最后的拓扑结果。用vector记录不断加入的入度为0的节点即可。
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>();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值