013寻找有向环

图学习笔记索引

图学习笔记索引(全部)
001自定义输入流In类实现
002背包数据类型Bag实现
003无向图数据类型实现
004基于图的深度优先搜索
005使用深度优先搜索找图中的所有连通分量
005-1基于深度优先搜索查找图中连通路径
006基于深度优先搜索判断图中是否存在环
007基于深度优先搜索判断一个无向图图是否是一个二分图
008广度优先搜索查找连通图中的最短路径
009有向图数据类型实现
010有向图的可达性
011带权重的无向边数据类型Edge实现
012加权无向图数据类型实现

1.寻找有向环

从文件中读取无向图图的顶点关系。
tinyDG.txt中的内容:
13
22
4 2
2 3
3 2
6 0
0 1
2 0
11 12
12 9
9 10
9 11
8 9
10 12
11 4
4 3
3 5
7 8
8 7
5 4
0 5
6 4
6 9
7 6

package algorithms.graph; 
import java.io.IOException;
import java.util.Stack;
/*
 * 寻找有向环
 * */
public class DirectedCycle {
    private boolean marked[];
    private int edgeTo[];
    private Stack<Integer> cycle;
    private boolean onStack[];
    public DirectedCycle(Digraph D){
    	marked = new boolean[D.V()];
    	edgeTo = new int[D.V()];
    	onStack = new boolean[D.V()];
    	for(int s = 0; s < D.V(); s++)
    		if(!marked[s])
    		   dfs(D, s);
    }
    public void dfs(Digraph D, int v){
    	onStack[v] = true;
    	marked[v] = true; 
    	for(int w : D.adj(v)) 
    		if(this.hasCycle()) return;
    		else if(!marked[w]){
    			edgeTo[w] = v;
    			dfs(D, w);
    		} 
    		else if(onStack[w]){
    			cycle = new Stack<Integer>();
    			for(int x = v; x != w; x = edgeTo[x]) 
    				cycle.push(x); 
    			cycle.push(w);
    			cycle.push(v); 
    		}
    	onStack[v] = false; //递归每层返回前每个顶点onStack[v] = false
    }
    public boolean hasCycle(){
    	return cycle != null;
    }
    public Iterable<Integer> getCycle(){
		return cycle; 
    }
    public boolean getOnStack(int v){
    	return this.onStack[v];
    }
	public static void main(String[] args) throws IOException {
		In in = new In("D:\\tinyDG.txt"); 
		Digraph D = new Digraph(in);
		System.out.println(D); 
		DirectedCycle dCycle = new DirectedCycle(D);
		System.out.println(dCycle.hasCycle());
		for(int v : dCycle.getCycle())
			System.out.print(v+"-");
		System.out.println();
		for(int v = 0; v < D.V(); v++)
			System.out.println(v + ": "+ dCycle.getOnStack(v));
	}

}

输出:

13 vectors; 22 edges
0: 5 1 
1: 
2: 0 3 
3: 5 2 
4: 3 2 
5: 4 
6: 9 4 0 
7: 6 8 
8: 7 9 
9: 11 10 
10: 12 
11: 4 12 
12: 9 

true
3-4-5-3-
0: true
1: false
2: true
3: true
4: true
5: false
6: true
7: true
8: true
9: true
10: true
11: true
12: true

2.总结

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值