dfs判环+输出环上元素

判环用什么?

用tarjan?拓扑排序?

其实都不用,用dfs+栈即可解决问题。(前提是不考虑时间复杂度)

我们只需要一个bool数组in_stack,每dfs到一个点,把点压入栈中,并把in_stack设为true,如果访问到一个节点已经在栈中,就依次取出栈中元素直到取到访问到的那个节点为止。

Code

int n,g[maxn][maxn],st[maxn],top;
bool oncyc[maxn],inst[maxn];
void getcyc(int u){
    st[++top]=u;
    inst[u]=1;
    int count=0;
    for(int v=1;v<=n;v++){
        if(!g[u][v])continue;
        count+=g[u][v];
        if(!inst[v]){
            getcyc(v);
        }
        else{
            int t;
            for(t=top;st[t]!=v;t--);
            for(int i=t;i<=top;i++){
                printf("%d ~ ",st[i]);
            }
            puts("");
    }
    top--;
    inst[u]=0;
}

转载于:https://www.cnblogs.com/BlogOfchc1234567890/p/9871108.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值