207. Course Schedule - Medium

课程完成可能性判断
本文介绍了一种使用拓扑排序的方法来判断给定一系列课程及其先修条件后,是否有可能完成所有课程的问题。通过DFS实现拓扑排序,有效地解决了课程依赖中的环路检测问题。

Description

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?

Example:
Input: 2, [[1,0]]
Output: true
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
Input: 2, [[1,0],[0,1]]
Output: false
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.

Code

判断是否有环,可以用拓扑排序求解。话不多说,直接上代码。

class Solution {
private:
    vector< vector<int> > V;
    vector<int> vis; // -1访问过一次,0没访问过,1访问完了 
    bool dfs(int u) {
        int v, i;
        vis[u] = -1;
        for (i=0; i<V[u].size(); i++) {
            v = V[u][i];
            if (!vis[v]) dfs(v);
            if (vis[v] == -1) return false;
        }
        vis[u] = 1;
        return true;
    }
public:
    bool canFinish(int n, vector< pair<int, int> >& edges) {
        int i;
        V.resize(n);
        vis.resize(n);
        for(int i = 0; i < edges.size(); ++i)
            V[edges[i].first].push_back(edges[i].second);
        for (i=0; i<n; i++) vis[i] = 0;
        for (i=0; i<n; i++)
            if (!vis[i]) {
                if(!dfs(i))  return false;
            }
        return true;
    }
};

Summary

1.拓扑排序有两种实现,一种是找入度为0的点;一种是DFS,DFS更高效一些。
2.如何检查环?
基于入度:如果找不到入度为0的点,但是依旧有为被访问过的节点,那就有环;
基于DFS:DFS有两种实现,递归版需要存储“黑白灰”三种状态,也就是我上面的做法;非递归版则可以判断邻居节点是否已经出现在栈中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值