检查图是否包含环

我们常常用检查一张图中是否包含环来判断是否可以对这张图进行拓扑排序。但是对于无向图,由于无向图中每条边都可以表示成其对应某点的入边和出边,所以不能用拓扑排序的方法来检查是否包含环。但是我们可以用DFS方法来进行检查:从某一个点开始进行DFS遍历,如果在某个点所连接的点中,包含一个已经经过过的且不是这个点的父节点的点,说明有环。
代码:

//有向图
bool checkLoop(vector<vector<int>>& graph,vector<int>& inDegree){
    int n = graph.size();
    vector<bool> v(n,false); //检查点是否被经过过
    queue<int> vv(n,true);//入度为0的点
    vector<int> in = inDegree;
    for(int i = 0;i < n;++i)
        if(in[i] == 0)
            vv.push(i);
    while(vv.size()){
        int x = vv.front();
        vv.pop();
        v[x] = true;
        for(int i = 0;i < n;++i)
            if(graph[x][i] == 1 && v[i] == false){
                in.push(i);
                --in[i];
                if(in[i] == 0)
                    vv.push(i);
            }
    }
    for(int i = 0;i < n;++i)
        if(v[i] == false)
            return true;
    return false;
}
//无向图
bool checkLoop(vector<vector<int>> &graph)
{
    int n = graph.size();
    stack<int> v;
    vector<pair<bool,int>> through(n, make_pair(false,0));//bool表示有没有through,int表示父节点
    v.push(0);
    while (v.size()) {
        int x = v.top();
        v.pop();
        if (through[x].first)continue;
        through[x].first = true;
        for (int i = 0; i < n; ++i) {
            if (graph[x][i] == 1) {
                if (through[i].first && through[i].second != i)
                    return true;
                else if (!through[i].first) {
                    v.push(i);
                    through[i] = make_pair(false, x);
                }
            }
        }
        for (int i = 0; i < n; ++i)
            if (!through[i].first)
                return true;
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值