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

/**
 * 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);//入队
				}
			}
		}					
	}
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/okiwilldoit/article/details/40654351
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞