图的深度遍历和广度遍历(用邻接表的方式)

/**
 * public class GraphNode {
	int label;
	List<GraphNode> neighbors;
	GraphNode(int x) { label = x; neighbors = new ArrayList<GraphNode>(); }
}
 */
public class graphTravel {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GraphNode graph = new GraphNode(0);
		List<GraphNode> neighbors = new ArrayList<GraphNode>();
		graph.neighbors = neighbors;
		
		GraphNode g1 = new GraphNode(1);
		GraphNode g2 = new GraphNode(2);
		GraphNode g3 = new GraphNode(3);
		neighbors.add(g1);
		neighbors.add(g2);
		neighbors.add(g3);
		
		List<GraphNode> neighbors1 = new ArrayList<GraphNode>();
		g1.neighbors=neighbors1;
		neighbors1.add(new GraphNode(4));
		neighbors1.add(new GraphNode(5));
				
		Map<GraphNode,Boolean> map = new HashMap<GraphNode,Boolean>();
		System.out.println("深度优先遍历");
		DepthFirstTravel(graph,map);
		
		System.out.println("广度优先遍历");
		BroadFirstTravel(graph);
	}
	
	/**
	 * 深度优先遍历,递归实现,需map判断是否访问过
	 */
	public static void DepthFirstTravel(GraphNode graph,Map<GraphNode,Boolean> map){
		if(graph == null)return;
		System.out.println(graph.label);
		map.put(graph, true);
		List<GraphNode> neighbors = graph.neighbors;
		for(GraphNode n:neighbors){
			if(!map.containsKey(n)){
				DepthFirstTravel(n,map);
			}
		}
	}
	
	/**
	 * 广度遍历,用队列实现,需要布尔map判断是否访问过
	 */
	public static void BroadFirstTravel(GraphNode graph){
		if(graph == null)return;
		Map<GraphNode,Boolean> map = new HashMap<GraphNode,Boolean>();
		Queue<GraphNode> queue = new ArrayDeque<GraphNode>();
		queue.offer(graph);
		map.put(graph, true);
		GraphNode n = null;
		while(!queue.isEmpty()){
			n = queue.poll();//出队
			if(n!=null && !map.containsKey(n)){
				System.out.println(n.label);
				map.put(n, true);
				for(GraphNode ch:n.neighbors){
					queue.offer(ch);//入队
				}
			}
		}					
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值