LintCode 1366.Directed Graph Loop 判断有向图是否有环

Description
Please judge whether there is a cycle in the directed graph with n vertices and m edges. The parameter is two int arrays. There is a directed edge from start[i] to end[i].

2 <= n <= 10^5
1 <= m <= 4*10^5
1 <= start[i], end[i] <= n
Have you met this question in a real interview?
Example
Given start = [1],end = [2], return “False”。

Explanation:
There is only one edge 1->2, and do not form a cycle.

思路:构建图结构,记录每个顶点的入度,若有后向边存在(拓扑结构中后出现的点有指向已出现的点的边),则有环。、

class Solution {
public:
    /**
     * @param start: The start points set
     * @param end: The end points set
     * @return: Return if the graph is cyclic
     */
    bool isCyclicGraph(vector<int> &start, vector<int> &end) {

        int n = 0;
        for(int s:start) n = max(n, s);
        for(int e:end) n = max(n, e);
        vector<int> graph[n+1];
        vector<int> d(n+1); // 保留各顶点的入度,判断拓扑排序后是否有边存在
        for(int i=0; i<start.size(); ++i){
            graph[start[i]].push_back(end[i]);
            d[end[i]]++;
        }
        queue<int> que;
        for(int i=1; i<=n; ++i)
            if(graph[i].size() && !d[i]) que.push(i);
        while(!que.empty()){
            int v = que.front(); que.pop();
            for(int edge:graph[v]){
                d[edge]--;
                if(d[edge]==0) que.push(edge);
            }           
        }        
        for(int i=1; i<=n; ++i)
            if(d[i]) return true;
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值