第五周 拓扑排序

算法题目 : 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:

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

算法分析:

这就是典型的拓扑排序的问题了,问我们是否可以依次输出这些课并且不形成环。我们就可以用拓扑排序依次输出度为0的值,并用一个队列存入度为0的节点,然后依次出对,如果最后存在度不为0的节点,就说明存在环。应该就是这样。


算法代码(C++):

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<vector<int>> graph(numCourses, vector<int>(0));
        vector<int> inDegree(numCourses, 0);
        for (auto u : prerequisites) {
            graph[u[1]].push_back(u[0]);
            ++inDegree[u[0]];
        }
        queue<int> que;
        for (int i = 0; i < numCourses; ++i) {
            if (inDegree[i] == 0) que.push(i);
        }
        while (!que.empty()) {
            int u = que.front();
            que.pop();
            for (auto v : graph[u]) {
                --inDegree[v];
                if (inDegree[v] == 0) que.push(v);
            }
        }
        for (int i = 0; i < numCourses; ++i) {
            if (inDegree[i] != 0) return false;
        }
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值