【图】图的深度优先和宽度优先遍历

图的学习

宽度优先遍历

图的bfs要准备一个Set,因为图可能是可循环的。遍历方法如下

  • 队列弹出就打印
  • 它的直接邻居,没有进入过Set的就进队列和Set
// 从node出发,进行宽度优先遍历
public static void bfs(Node start) {
    
    
	if (start == null) {
    
    
		return;
	}
	Queue<Node> queue = new LinkedList<>();
	HashSet<Node> set = new HashSet<>();
	queue.add(start);
	set.add(start);
	while (!queue.isEmpty()) {
    
    
		Node cur = queue.poll();
		System.out.println(cur.value);
		for (Node next : cur.nexts) {
    
    
			if (!set.contains(next)) {
    
    
				set.add(next);
				queue.add(next);
			}
		}
	}
}

深度优先遍历

public static void dfs(Node node) {
    
    
	if (node == null) {
    
    
		return;
	}
	Stack<Node> stack = new Stack<>();
	HashSet<Node> set = new HashSet<>();
	stack.add(node);
	set.add(node);
	//入栈的时候就打印
	System.out.println(node.value);
	while (!stack.isEmpty()) {
    
    
		Node cur = stack.pop();//弹出节点
		for (Node next : cur.nexts) {
    
    //枚举子节点
			if (!set.contains(next)) {
    
    //如果set中不包含next
				stack.push(cur);//把父节点重新压入栈
				stack.push(next);//压入子节点
				set.add(next);//set记录子节点
				System.out.println(next.value);//压入栈时候打印
				break;//退出循环
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/VanGotoBilibili/article/details/115295575