数据结构-图-是否存在环(Java语言)

 

详细的代码可见github:

https://github.com/AbitGo/myClassWork/tree/master/workspace_ds

如何实现判断改图存在有向环

 

详细代码实现:

package com.company.ch6;

import com.company.ch3.Stack.LinkStack.LinkStack;

public class Exp6_3 {
    //访问标志数组
    private boolean[] visited;
    private LinkStack s = new LinkStack();
    //表示是否已经找到了环
    private boolean find = false;

    public void findCircle(IGraph g)throws Exception{
        visited = new boolean[g.getVexNum()];
        for(int i = 0;i<g.getVexNum();i++){
            visited[i]=false;
        }
        for(int v = 0;v<g.getVexNum();v++){
            if(!visited[v]){
                find_DFS(g,v);
            }
        }
        if(find){
            System.out.println("该有向图存在环");
        }else{
            System.out.println("该有向图不存在环");
        }
    }

    public void find_DFS(IGraph g,int v) throws Exception {
        if(!find){
            visited[v]=true;
            s.push(v);
            for(int w = g.firstAdjVex(v);w>=0;w=g.nextAdjVex(v,w)){
                if(visited[v]&&isDuplicate(w)){
                    find = true;
                }else {
                    find = false;
                }
            }
            s.pop();
        }
    }

    private boolean isDuplicate(Integer w)throws Exception{
        //辅助栈
        LinkStack stack = new LinkStack();
        while(!s.isEmpty() && !((Integer)s.peek()).equals(w)){
            stack.push(s.pop());
        }
        if(s.isEmpty()){
            while(!stack.isEmpty()){
                s.push(stack.pop());
            }
            return false;
        }else
            return true;

    }

    public static void main(String[] args) throws Exception {
        ArcNode ab = new ArcNode(1);
        VNode A = new VNode("A",ab);

        ArcNode bc = new ArcNode(1);
        ArcNode be = new ArcNode(4,0,bc);
        VNode B = new VNode("B",be);

        ArcNode cd = new ArcNode(3);
        VNode C = new VNode("C",cd);

        ArcNode de = new ArcNode(4);
        VNode D =new VNode("D",de);

        ArcNode ef = new ArcNode(5);
        VNode E =new VNode("E",ef);

        ArcNode fa = new ArcNode(0);
        ArcNode fb = new ArcNode(1,0,fa);
        VNode F =new VNode("F",fb);

        VNode[] ves = {A,B,C,D,E,F};
        ALGraph g = new ALGraph(GraphKind.DG,6,8,ves);
        Exp6_3 exp6_3 = new Exp6_3();
        exp6_3.findCircle(g);
    }
}

测试结果:

"C:\Program Files\Java\jdk1.8.0_101\bin\java.exe" 
该有向图存在环

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值